0
long long int big_mod(long long int base, long long int power, long long int mod)
{
    if(power==0)    return 1;
    else if(power%2==1)
    {
        int p1 = base % mod;
        int p2 = (big_mod(base,power-1,mod))%mod;
        return (p1*p2)%mod;
    }
    else if(power%2==0)
    {
        int p1 = (big_mod(base,power/2,mod))%mod;
        return (p1*p1)%mod;
    }
}

this function returns negative value for (3 140068687 419634856) input. why is this happening? Can anyone explain please.

  • 2
    Because your multiplication is overflowing. – Barmar Apr 07 '20 at 21:53
  • what should I change in my code to get correct value for these inputs? @Barmar – Sadik AL Barid Nebir Apr 07 '20 at 22:02
  • You need to study the mathematics of modular arithmetic to see if there's a way to do this without doing the multiplication. – Barmar Apr 07 '20 at 22:06
  • You did not add your header files, which could help us to determine your calculation limits. Basically, your limits are bound by cpu architecture and the compiler abilities. you could use lldb or gdb to see your results in accumulators. then you can be sure that it's overflow or something else – hatirlatici Apr 07 '20 at 22:17

1 Answers1

1

The value of returning may be too big (p1*p2 and p1*p1), it makes your program overflowing.

Use (A * B) mod C = (A mod C * B mod C) mod C to calculate the modular

So you can change the return value:

else if(power%2==1)
{
     ...
     return ((p1%mod) * (p2%mod))%mod;
}
else if(power%2==0)
{
     ...
     return ((p1%mod) * (p1%mod))%mod;
}
Hitokiri
  • 3,607
  • 1
  • 9
  • 29