Finding the exponent of any number can be very troublesome as it grows exponentially. But in this problem you will have to do a very simple task. Given two non-negative numbers m and n, you will have to find the last digit of mn in decimal number system. Input The input file contains less than 100000 lines. Each line contains two integers m and n (Less than 10101. Input is terminated by a line containing two zeroes. This line should not be processed. Output For each set of input you must produce one line of output which contains a single digit. This digit is the last digit of mn. Sample Input 2 2 2 5 0 0 Sample Output 4 2
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long ll;
char b[1000010],n[1000010];
ll power(ll a,ll b,ll p)
{
ll ans=1%p;
for(; b; b>>=1)
{
if(b&1)
ans=ans*a%p;
a=a*a%p;
}
return ans;
}
ll phi(ll n)
{
ll ans=n;
for(ll i=2; i<=sqrt(n); i++)
if(n%i==0)
{
ans=ans/i*(i-1);
while(n%i==0)
n/=i;
}
if(n>1)
ans=ans/n*(n-1);
return ans;
}
int main()
{
ll p;
while(scanf("%s%s",b,n))
{
if(b[0]=='0'&&n[0]=='0')
break;
p=10;
ll k=phi(p),lengthb=strlen(b),lengthn=strlen(n),b1=0,n1=0;
for(ll i=0; i<lengthb; i++)
b1=(b1*10+(b[i]-'0'))%p;
bool flag=false;
for(ll i=0; i<lengthn; i++)
{
n1=(n1*10+n[i]-'0');
if(n1>=k)
n1%=k,flag=true;
}
if(flag)
n1+=k;
ll ans=power(b1,n1,p);
printf("%lld\n",ans);
}
return 0;
}