I implemented the exponential by squaring in java. And copied from net, a C code for the same. But the problem is, these codes are giving different outputs.
The input i am giving is: 2 as base and 999999999 and 1000000000 as powers.
here is my java code:
long power(int b,int i){
long num;
if(i==1)
return b;
else if(i%2==0){
num=(long)Math.pow(power(b,i/2),2);
if(num>=1000000007)
num%=1000000007;
return num;
}
else{
num=b*(long)Math.pow(power(b,(i-1)/2),2);
if(num>=1000000007)
num%=1000000007;
return num;
}
}
output: 646458262 178281319
here is the C code i got from net:
long long int fast_exp(int base, int exp)
{
if(exp==1)
return base;
else
{
if(exp%2 == 0)
{
long long int base1 = pow(fast_exp(base, exp/2),2);
if(base1 >= 1000000007)
return base1%1000000007;
else
return base1;
}
else
{
long long int ans = (base* pow(fast_exp(base,(exp-1)/2),2));
if(ans >= 1000000007)
return ans%1000000007;
else
return ans;
}
}
}
output: 646458006 477022294