Cod sursa(job #1152416)

Utilizator clopotelNeamtu Sergiu clopotel Data 24 martie 2014 18:27:06
Problema Ridicare la putere in timp logaritmic Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <string.h>
#define mm 1999999973
using namespace std;
ifstream fin("lgput.in");
ofstream fout("lgput.out");
unsigned long long int n,p;
unsigned long long int ex(unsigned long long int x,unsigned long long int n)
{
    if(n<0)
        return ex(1/x,-n);
    else
    {
        if(n==0)
            return 1;
        else
        {
            if(n==1)
                return x;
            else
            {
                if(n%2==0)
                {
                    if(x*x>=mm)
                        return ex((x*x)%mm, n/2);
                    else
                        return ex(x*x, n/2);
                }
                else
                {
                    if(n%2==1)
                    {
                        if(x*x>=mm)
                            return x*ex((x*x)%mm, (n-1)/2);
                        else
                            return x*ex(x*x, (n-1)/2);
                    }
                }
            }
        }
    }
    return 0;
}
int main()
{
    fin>>n>>p;
    fout<<ex(n,p)%mm;
    return 0;
}