CSU— E: Exponial
2018-04-01 23:31
162 查看
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⋅...⋅422016 times422016=42⋅42⋅...⋅42⏟2016 times.Factorials: 2016!=2016 ⋅ 2015 ⋅ ... ⋅ 2 ⋅ 1.
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
思路:这题非常的幸运,最近刚看的数论的部分有道关于幂运算的题,我记e(n)=exponial(n),由指数循环定理
AB mod C=AB mod φ(C)+φ(C) mod C(B>φ(C)),由于e(5)=5218>109,故只要n>4就满足指数循环定理的条件,进而有e(n)%m=nφ(m)⋅ne(n−1)%φ(m)%m,以此递推即可。当n<5的时候直接暴力就可以了。这题有个巨坑的点,我开始满心欢喜写出来然后过了样例以为对了,一提交就wa,再提交还是wa,最后发现是没有多组输入。所以以后不管做什么,第一件事就是给多组输入。不要偷懒。!!!!#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
typedef long long ll;
ll n,m,ans;
ll fun1(ll n)
{
ll r=n,a=n;
for(ll i=2;i*i<=a;i++)
{
if(a%i==0)
{
r=r/i*(i-1);//防止数据太大溢出
while(a%i==0)
{
a/=i;
}
}
}
if(a>1)
{
r=r/a*(a-1);
}
return r;
}
ll fun2(ll x,ll n,ll maxn)
{
ll r=1;
while(n>0)
{
if(n&1)
{
r=(r*x)%maxn;
}
x=(x*x)%maxn;
n>>=1;
}
return r;
}
ll fun3(ll n,ll 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 fun2(4,9,m);
}
else
{
ll phi=fun1(m);
ll z=fun3(n-1,phi);
ans=fun2(n,phi+z,m);
}
return ans;
}
int main()
{
while(cin>>n>>m)
cout<<fun3(n,m)<<endl;
return 0;
}
相关文章推荐
- CSU Double Shortest Paths 湖南省第十届省赛
- CSU 1337 搞笑版费马大定理
- CSU_1673_集训队组队计划
- csu 1303 Decimal
- CSU 1556 快速幂
- CSU_1216(异或最大值)
- CSU 1604: SunnyPig
- 双向链表 csu1692 Vector Field
- CSU 1558 和与积
- ACM--字符串--CSU--1550-- Simple String
- CSU 1725 加尔鲁什·地狱咆哮对阵虚灵大盗拉法姆
- CSU1320(详解卡特兰数)
- CSU-ACM2016暑假集训比赛3
- CSU1008 Horcrux (模拟)
- 数学 ( 卡特兰数 )——Scoop water ( CSU 1320 )
- csu 1755 阶数(欧拉函数)
- CSU-ACM2016暑假集训比赛11
- CSU 1781 NBUT - 1643 阶乘除法
- csu 1020 真三国无双
- csu 1550(字符串处理思路题)