2xmodn=1

HDU 1395 2^x mod n = 1

  • 题目描述

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

  • Inuput

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

  • Tips:

题意:
求最小正整数x,使其满足2x mod n = 1,若找不到,则输出2^? mod n = 1.


分析:

由欧拉定理:

FQgsc6.png

若n, a为正整数,且n, a互质,则

FQg2He.png

当2,n互质时,一定存在x,使

而当n = 1 或n为偶数时,2x mod n 不可能为1
所以分情况:

1°
当输入的n = 1 || n % 2 == 0时,输出

2^? mod n = 1

2°
当输入的n ≥ 3 && n % 2 == 1时,暴力穷举i = 1 … INF.使用快速幂计算2i mod n是否为1,若为1则输出并break,否则i++.

因为测试数据较小,即使用暴力发也能AC.(但会卡cout所以请使用printf()).

  • Answer:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int n;
int pow(long long i){
	
	int ans = 1, base = 2;
	while(i){
		if(i & 1){
			ans = ans * base % n; 
		}
		base = base * base % n;
		i >>= 1;
	}
	return ans % n;

}
int main(void){

	while(cin >> n){
	
	if(n % 2 == 0 || n == 1 ){
		printf("2^? mod %d = 1\n", n); 
	}
	else{
		for(long long i = 1; ;i++){
			if(pow(i) == 1)
			{
				printf("2^%lld mod %d = 1\n", i, n);
				break;
			}
		}
	}
}
	return 0;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值