数论 CSU2021 降幂公式 NCPC2016

16 篇文章 0 订阅

2021: Exponial

Submit Page    Summary    Time Limit: 1 Sec     Memory Limit: 512 Mb     Submitted: 243     Solved: 98    


Description

Everybody loves big numbers (if you do not, you might want to stop reading at this point). There are many ways of constructing really big numbers known to humankind, for instance:

  • Exponentiation: 422016=42⋅42⋅...⋅422016 times422016=42⋅42⋅...⋅42⏟2016 times.
  • Factorials: 2016!=2016 ⋅ 2015 ⋅ ... ⋅ 2 ⋅ 1.

Illustration of exponial(3) (not to scale), Picture by C.M. de Talleyrand-Périgord via Wikimedia Commons

In this problem we look at their lesser-known love-child the exponial, which is an operation defined for all positive integers n​ as 
exponial(n)=n(n − 1)(n − 2)⋯21
For example, exponial(1)=1 and exponial(5)=54321 ≈ 6.206 ⋅ 10183230 which is already pretty big. Note that exponentiation is right-associative: abc = a(bc).

Since the exponials are really big, they can be a bit unwieldy to work with. Therefore we would like you to write a program which computes exponial(n) mod m (the remainder of exponial(n) when dividing by m).

Input

There will be several test cases. For the each case, the input consists of two integers n (1 ≤ n ≤ 109) and m (1 ≤ m ≤ 109).

Output

Output a single integer, the value of exponial(n) mod m.

Sample Input

2 42
5 123456789
94 265

Sample Output

2
16317634
39

 

太大了太大了,用降幂公式,并进行递归!

注!:公式的适用条件:K > \varphi(m)  !

           所以!前四个(1<=n<=4)特判!!!

 

#include <cstdio>

long long n,m;
long long mod;

long long phi(long long x)
{
    long long res=x;
    for(long long i=2;i*i<=x;++i){
        if(x%i==0){
            res=res-res/i;
            while(x%i==0)
                x/=i;
        }
    }
    if(x>1)
        res=res-res/x;
    return res;
}

long long qpow(long long a,long long n,long long mod)
{
    long long res=1;
    while(n){
        if(n&1){
            res*=a;
            res%=mod;
        }
        n>>=1;
        a=(a*a)%mod;
    }
    return res;
}

long long solve(long long n,long long m)
{
    if(m==1) return 0;
    if(n==1) return 1;
    else if(n==2) return 2%m;
    else if(n==3) return 9%m;
    else if(n==4) return qpow(4,9,m);     //降幂公式适用条件!前4个特判!
    long long tem=phi(m);
    return qpow(n,solve(n-1,tem)+tem,m);
}

int main()
{
    while(~scanf("%lld%lld",&n,&m)){
        printf("%lld\n",solve(n,m));
    }

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值