Codeforces Beta Round #17 D. Notepad (尤拉廣義降冪)
D. Notepad
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
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 < , 1 ≤ n < , 1 ≤ c ≤ ). 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.
題意:
給你一個b進位制,問b進位制位有n位的不同數有多少個,把這些數寫在紙上,最後一頁寫了多少個?
題解:
b進位制每位只能是 0 ~ b-1,最高為不能為0,所以最高位只有b-1中選擇,其他位都有b種選擇,所以得出公式:
,餘數為0,則答案為c
AC程式碼:
#include<iostream>
#include<string.h>
#include<cstdio>
using namespace std;
typedef long long ll;
const int MAXN = 1e6+66;
char b[MAXN],n[MAXN];
ll Eular(ll c) //尤拉函式值phi()
{
ll phi = c;
for(int i=2;i*i<=c;++i)
{
if(c%i==0)
{
phi = phi - phi/i;
while(c%i==0)
c = c/i;
}
}
if(c>1) phi = phi - phi/c;
return phi;
}
ll quick_pow(ll a,ll x,ll mod) //快速冪
{
ll ans = 1;
while(x)
{
if(x&1) ans = ans*a % mod;
a = a*a % mod;
x = x>>1;
}
return ans % mod;
}
ll cal(char *s,ll mod) //取模得到b值
{
ll res = 0;
for(int i=0;i<strlen(s);++i)
res = (s[i]-'0'+res*10) % mod;
return res;
}
int main()
{
int c;
scanf("%s %s %d",b,n,&c);
ll bb = cal(b,c);
ll phi = Eular(c);
bool vis = false; //標記n-1是否大於phi(c)
ll nn = 0;
for(int i=0;i<strlen(n);++i) //計算n值
{
nn = n[i]-'0'+ nn*10;
if(nn>=phi+1)
{
vis = true;
nn = nn % phi;
}
}
if(vis) nn += phi; //尤拉廣義降冪
ll ans = (quick_pow(bb,nn-1,c)*(bb-1)+c)%c;
if(ans) cout<<ans;
else cout<<c;
return 0;