您的位置:首页 > 其它

HDOJ1395 2^x mod n = 1

2017-12-08 17:05 197 查看

2^x mod n = 1

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 18046    Accepted Submission(s): 5656


[align=left]Problem Description[/align]
Give a number n, find the minimum x(x>0) that satisfies 2^x mod n = 1.

 

[align=left]Input[/align]
One positive integer on each line, the value of n.

 

[align=left]Output[/align]
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.

 

[align=left]Sample Input[/align]

2
5

 

[align=left]Sample Output[/align]

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

 可以使用暴力法直接解决。不过在每次乘的时候都求一次余。
import java.util.Scanner;

//2^x mod n = 1.
public class Main{
private static Scanner scanner;

public static void main(String[] args) {
scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
int x = 1;
boolean isMod = false;
for (int i = 1; i <= n; i++) {
x = x * 2 % n;
if (x == 1) {
System.out.println("2^" + i + " mod " + n + " = 1");
isMod = true;
break;
}
}
if (!isMod) {
System.out.println("2^? mod " + n + " = 1");
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: