time limit per test:2 seconds
memory limit per test:64 megabytes
Nick is attracted by everything unconventional. He doesn’t like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick’s notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.
Would you help Nick find out how many numbers will be written on the last page.
Input
The only input line contains three space-separated integers b, n and c (2 ≤ b < 10^(10^6), 1 ≤ n < 10^(10^6), 1 ≤ c ≤ 10^9). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn’t contain leading zeros.
Output
In the only line output the amount of numbers written on the same page as the last number.
Examples
Input
2 3 3
Output
1
Input
2 3 4
Output
4
【题意】输入3个数b,n,c,意思是将所有的b进制的n位数写在一本本子上,本子每面可以写c个数,求最后一面写了多少个数。
【解题思路】 由题意可以得出答案公式为ans=(b-1)*b^(n-1)%c,若ans=0,说明最后一面写满了,由于数据很大,输入都只能用字符串,故在此引用求幂大法——a^b≡a^(b%φ(m)+φ(m))(mod m),若b<φ(m),则a^b≡a^(b%φ(m))(mod m),φ(m)是指m的欧拉值。
【AC代码】
#include<stdio.h>
#include<string.h>
#define ll __int64
using namespace std;
char a[1000005],b[1000005];
ll power(ll x,ll y,ll z)
{
ll ans=1;
while(y)
{
if(y&1)
ans=(ans*x)%z;
x=(x*x)%z;
y/=2;
}
return ans;
}
int oula(ll x)
{
int num=1,i;
for(i=2;i*i<=x;i++)
if(x%i==0)
{
x/=i;
num*=i-1;
while(x%i==0)
{
x/=i;
num*=i;
}
}
if(x>1)
num*=x-1;
return num;
}
int main()
{
int i;
ll m=0,n=0,c,d,m1;
scanf("%s%s%I64d",a,b,&c);
int lena=strlen(a);
int lenb=strlen(b);
d=(ll)oula(c);
for(i=0;i<lena;i++) //求a
m=(a[i]-'0'+m*10)%c;
m1=(m+c-1)%c;
for(i=lenb-1;i>=0;i--) //求b-1
{
if(b[i]=='0')
b[i]='9';
else
{
b[i]--;
break;
}
}
int vis=0;
for(i=0;i<lenb;i++)
{
if(n>=d) //判断b是否大于φ(c)
vis=1;
vis?n=(b[i]-'0'+n*10)%d:n=b[i]-'0'+n*10;
if(vis)
n+=d;
ll ans=power(m,n,c);
ans=(ans*m1)%c;
if(ans==0)
ans=c;
printf("%I64d\n",ans);
return 0;
}