hdu 2837 Calculation

公式:a^b%p=a^(b%phi(p)+phi(p))%p   b>=phi(p)

 1 #include<iostream>

 2 #include<stdio.h>

 3 #include<algorithm>

 4 #include<iomanip>

 5 #include<cmath>

 6 #include<string>

 7 #include<vector>

 8 #define ll __int64

 9 using namespace std;

10 ll euler(int n)

11 {

12     ll ans=1;

13     for(int i=2;i*i<=n;i++)

14     {

15         if(n%i==0)

16         {

17             ans*=i-1;

18             n/=i;

19             while(n%i==0)

20             {

21                 ans*=i;

22                 n/=i;

23             }

24         }

25     }

26     if(n>1) ans*=n-1;

27     return ans;

28 }

29 ll pows(ll a,ll b,ll m)

30 {

31     ll ans=1;

32     while(b)

33     {

34         if(b&1) ans=(ans*a)%m;

35         b>>=1;

36         a=(a*a)%m;

37     }

38     return ans%m;

39 }

40 ll cmp(int a,int b,int m)

41 {

42     ll ans=1;

43     for(int i=1;i<=b;i++)

44     {

45         ans*=a;

46         if(ans>=m) return ans;

47     }

48     return ans;

49 }

50 ll fun(int n,int m)

51 {

52     ll phi=euler(m);

53     if(n<10) return n;

54     ll a=fun(n/10,phi);

55     ll b=cmp(n%10,a,m);

56     if(b>=m) 

57     {

58         ll ans=pows(n%10,a+phi,m);

59         if(ans==0)

60             ans+=m;

61         return ans;

62     }

63     return b;

64 }

65 int main()

66 {

67     int t,i,j,m,n;

68     cin>>t;

69     while(t--)

70     {

71         cin>>n>>m;

72         ll ans=fun(n,m)%m;

73         printf("%I64d\n",ans);

74     }

75     return 0;

76 }
View Code

 

你可能感兴趣的:(HDU)