Calculation HDU - 2837 欧拉降幂 坑死人了原来还有这种细节

博客目录

原题

传送门

Assume that f(0) = 1 and 0^0=1. f(n) = (n%10)^f(n/10) for all n bigger than zero. Please calculate f(n)%m. (2 ≤ n , m ≤ 10^9, x^y means the y th power of x).

Input

The first line contains a single positive integer T. which is the number of test cases. T lines follows.Each case consists of one line containing two positive integers n and m.

Output

One integer indicating the value of f(n)%m.

Sample Input

2
24 20
25 20

Sample Output

16
5

解析

a^b mod c

可以转化为

a^(b mod phi(c)+phi(c)) mod c(b>phi(c)时成立)

所以要注意取模的时候 b<mod则不管,b>=mod时   b=b%mod+mod

AC代码

#include<bits/stdc++.h>
#include<cstring>
using namespace std;
typedef long long ll;
ll Oula(ll n)
{
	 ll ans=n;
	 for(int i=2;i<=(double)sqrt(n*1.0);i++)
	 {
	 	if(n%i==0)
	 		ans=ans*(1.0-1.0/i);
	 	while(n%i==0)
	 		n=n/i;
	 }
	 if(n>1)
	 	 ans=ans*(1.0-1.0/n);
	 return ans;
}
ll qpow(ll a, ll b, ll mod)
{
	 ll ans=1;
	 while(b)
	 {
	 	 if(b&1)
	 	 {
	 	 	
	 	 	 ans=ans*a;
	 	 	 if(ans>=mod)
	 	 	 ans=ans%mod+mod;
	 	 }
	 	 a*=a;
	 	 if(a>=mod)
	 	 	 a=a%mod+mod;
	 	 b>>=1;
	 }
	 return ans;
}
ll f(int n,int m){
	if(n==0)
		return 1;
	if(n<10)
		return n;
	ll phi=Oula(m);
	return qpow(n%10,f(n/10,phi),m);
}
int main(){
	ll mod;
	ll T,n;
	cin>>T;
	while(T--){
		cin>>n>>mod;
		cout<<f(n,mod)%mod<<endl;
	}
}

猜你喜欢

转载自blog.csdn.net/GreyBtfly/article/details/82778326