OJ小练之“2^x mod n = 1”

Problem description
Give a number n, find the minimum x 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
Problem Source
MA, Xiao

 

题目简析:输入一个整数n,求2的几次幂模n等于1.

 

思路:当n为2的倍数或者为1时,2的幂模n不可能为1;否则,循环乘以二并且判断模n是否为1.

 

遇到的问题:

1.循环输入且无结束标志时:

int n;

while(cin>>n&&n!=EOF){

}

这样,当输入结束,按ctrl+z,再回车就ok 啦;

2.2的幂可以无限大,题目没有给出数据范围:找出特殊值(有可能陷入死循环的值),单独处理,其他用while(1)循环,在循环里面写好跳出条件。

3.超时问题:在效果相同的前提下,尽量使数据减小,比如这题中我用while(1)循环中的s%=n,是s尽可能小。

 

代码:

#include <iostream>
using namespace std;
int main(){
	int s=1,i=0,n;	
	while(cin>>n&&n!=EOF){
		i=0,s=1;
		if(n%2==0||n==1){
			cout<<"2^? mod "<<n<<" = 1"<<endl;
		}
		else{
			while(1){
				s*=2;
				i++;
				s%=n;//这一步防止超时 
				if(s%n==1){
					cout<<"2^"<<i<<" mod "<<n<<" = 1"<<endl;break;
				}
				
			}
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值