Problem link-http://www.spoj.com/problems/LASTDIG/
Summary-Given 2 non negative integers a and b, print the last digit of a^b.
I tried using an algorithm to find the modular exponentiation using less memory space(http://en.wikipedia.org/wiki/Modular_exponentiation#Memory-efficient_method) but I am getting a TLE(Time Limit Exceeding) error for my solution. What changes should I make to run my code in within 1 second? Note that 10 test cases need to run within 1 second.
My solution:
#include<iostream>
#include<vector>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdlib>
typedef long long LL;
using namespace std;
int ME(LL A, LL B)
{
LL c=1;
int E=0;
while(E<B)
{
c=(c*A)%10;
E++;
}
return c;
}
int main()
{
int t;
LL a, b;
vector <int> lDigit(31);
cin>>t;
for(int i=0;i<t;i++)
{
cin>>a>>b;
if(b>=99999)
lDigit[i]=ME(a, b);
else
{
int temp=pow(a, b);
lDigit[i]=temp%10;
}
}
for(int i=0;i<t;i++)
cout<<lDigit[i]<<endl;
return 0;
}