2^x mod n = 1【费马小定理】

转载自https://blog.csdn.net/qq_37383726/article/details/67636835                              

2^x mod n = 1

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13617    Accepted Submission(s): 4212

Problem Description

Give a number n, find the minimum x(x>0) that satisfies 2^x mod n = 1.

Input

One positive integer on each line, the value of n.

Output

If the minimum x exists, print a line with 2^x mod n = 1.

Print 2^? mod n = 1 otherwise.

You should replace x and n with specific numbers.

Sample Input

2

5

Sample Output

2^? mod 2 = 1 2^4 mod 5 = 1

思路 一  费马小定理的运用:

n为偶数时 不会存在x 使得 2 的 x次方 对n取余为1;

n为1时也不会存在;

n为非1奇数时,则gcd(n,2)==1,故必存在一值x使得 2 的 x次方 对n取余为1。

思路 二

 用到数论上的乘法逆元的规律了。

乘法逆元:对于整数a、p如果存在整数b,满足a*b mod p = 1,则称

b是a的模p的乘法逆元。a存在模p的乘法逆元的充要条件是gcd(a,p) = 1

此题中,令a = 2^x,b = 1,p = n,则若存在x使得2^x mod N = 1,

则gcd(2^x,N) = 1。

1>.因为N>0,当N为偶数时,gcd(2^x,N) = 2*k(k=1,2,3……),不满足

2>.当N为奇数时,gcd(2^x,N) = 1满足条件。

3>.当N为1时,2^x mod N = 0,不符合条件

所以N为奇数,且不为1,满足2^x mod N = 1,暴力求解。

代码:暴力解法

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
	int n,i;
	int temp;
	while(scanf("%d",&n)!=EOF){
		temp=1;
		//cout<<temp2<<endl;
		if(n%2&&n>1){//如果为奇数,并且不是1,那么一定有解
		    for(i=1;;++i){
			    temp=temp*2%n;
			    if(temp==1){
				    printf("2^%d mod %d = 1\n",i,n);
				    break;	
			    }		
		    }			
		}
		else printf("2^? mod %d = 1\n",n);
	}
}

猜你喜欢

转载自blog.csdn.net/dadaguai001/article/details/81076762
今日推荐