0

There is some mistake in power function of my code it returns correct answer for small values but gives wrong answer for large values.

#include<stdio.h>
long long MOD= 1000000007;
long long power(long long i,long long j)
{
        if(j==0)
                return 1;
        long long d;
        d=power(i,j/(long long)2);
        if(j%2==0)
                return (d*d)%MOD;
        else
                return (d*d*i)%MOD;
}

int main()
{
        long long inv=1;
        inv=power(25,MOD-2)%MOD;
        printf("%lld\n",inv);
}
TLE
  • 705
  • 1
  • 7
  • 16

3 Answers3

1

Your arithmetic overflowed the values representable in a long long in your C implementation.

Also, you are working on a challenge problem or homework which has been discussed numerous times on Stack Overflow, as you can see by searching for “1000000007”.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • I have no problem with algorithm.I am having problem with c .In python I am getting correct result of same problem – TLE Mar 25 '13 at 13:36
0

You need to be careful with (d*d*i)%MOD;, because more than one operation without modulo is incorrect, taking precision and risk of overflowing in account. To be strictly correct you need to write

 return ((d*d)%MOD * i)%MOD;

Even in this case I assumed i == i%MOD

EDIT: I take an example :

log2((MOD-1)x(MOD-1)x25) = log2(1000000006x1000000006x25) = 64.438

Which means you will be overflowing during your computation with this input.

UmNyobe
  • 22,539
  • 9
  • 61
  • 90
0

range of signed long long is -2^63 to (2^63 - 1) and the last bit is used to store sign . In your case when multiplication of large numbers is evaluated than your result will overflow and 64th bit of number(which stores sign) will get value 1 (which means -ve value).

That's the reason you are getting negative value as output.

Read this

TLE
  • 705
  • 1
  • 7
  • 16