您的位置:首页 > 其它

【HDU】 1395 2^x mod n = 1

2016-05-30 20:21 375 查看

2^x mod n = 1

题目链接

2^x mod n = 1

题目大意

找到一个最小的x满足2x mod n = 1如果没有则输出2? mod n = 1

题解

我们可以把式子化为(2∗2x−1) mod n = 1 首先可以看到2x是个偶数,要想让该式成立肯定n不能为偶数或者是1,有了这个结论后我们就可以把式子化为(2∗(2x−1 mod n))mod n = 1于是我们设F(x−1) = 2x−1mod n 所以我们现在有

F(x)=(2∗F(x−1))mod n

一直推直到F(x)为1就行了。

代码

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

int n;

int main()
{
while(scanf("%d",&n)!=EOF)
{
if (n%2==0 || n==1)
{
printf("2^? mod %d = 1\n",n);
continue ;
}
else
{
int ans=1,cnt=0;
while (ans!=1 || cnt==0)
{
cnt++;
ans=(ans*2)%n;
}
printf("2^%d mod %d = 1\n",cnt,n);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: