TITLE: How do you calculate the modulo of a high-raised number?
QUESTION [31 upvotes]: I need some help with this problem:
$$439^{233} \mod 713$$
I can't calculate $439^{223}$ since it's a very big number, there must be a way to do this.
Thanks.

REPLY [7 votes]: Here`s the algorithm,basically it is Modular exponentiation.
function modular_pow(base, exponent, modulus)
  result := 1      
  while exponent > 0
      if (exponent mod 2 == 1):
         result := (result * base) mod modulus
      exponent := exponent >> 1
      base = (base * base) mod modulus
  return result

Also here is the working code in c++ which can work for upto 10^4 test cases,in 0.7 seconds
Also the ideone link http://ideone.com/eyLiOP
#include <iostream>
using namespace std;
#define mod 1000000007


long long int modfun(long long int a,long long int b)
{
     long long int result = 1;
    while (b > 0)
       {
           if (b & 1)
           {
               a=a%mod;
               result = (result * a)%mod;
               result=result%mod;
           }
        b=b>>1;
        a=a%mod;
        a = (a*a)%mod;
        a=a%mod;
       }
    return result;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
        {
           long long int a,b;
           cin>>a>>b;
           if(a==0)
            cout<<0<<"\n";
           else if(b==0)
            cout<<1<<"\n";
           else if(b==1)
            cout<<a%mod<<"\n";
           else
           {
               cout<<(modfun(a,b))%mod<<"\n";
           }

        }
    return 0;
}