Cod sursa(job #2422420)

Utilizator CoroloHorjea Cosmin Corolo Data 18 mai 2019 17:46:23
Problema Ridicare la putere in timp logaritmic Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>

#define REST 1999999973

using namespace std;

ifstream f("lgput.in");
ofstream g("lgput.out");

// int putere(int x, int n)
// {
//       if (n < 0)
//             return putere(1 / x, (-1) * n);
//       else if (n == 0)
//             return 0;
//       else if (n == 1)
//             return 1;
//       else if (n % 2 == 0)
//             return putere(x * x, n / 2);
//       else if (n % 2 == 1)
//             return (x * putere(x * x, (n - 1) / 2));
// }
long long exp_by_squareing(long long x, int n)
{
      if (n < 0)
      {
            x = 1 / x;
            n *= -1;
      }
      if (n == 0)
            return 1;
      long long y = 1;
      while (n > 1)
      {
            if (n % 2 == 0)
            {
                  x = x * x;
                  n /= 2;
            }
            else
            {
                  y = (x * y) % REST;
                  x = (x * x) % REST;
                  n = (n - 1) / 2;
            }
      }
      return (x * y);
}

int main()
{
      int N, P;
      f >> N >> P;
      f.close();
      g << exp_by_squareing(N, P);
      g.close();
}