[英]How to hold greater values for (2^(n-1) mod 1 =1) in JAVA
我正在嘗試解決SPOJ中的“素數生成器”,使用2 ^(n-1)%n == 1來查找素數,但是對於整數,它在某個時間點變長了,因此變得更大,因此我嘗試了BigInteger,甚至現在它不顯示輸出。
我已經嘗試了各種其他技術,但是它們顯然超出了時間限制,想嘗試除SOE算法之外的其他技術。
import java.io. * ;
import java.math. * ;
import java.util. * ;
import java.util.Scanner;
class Scratch {
public static void main(String[] args) {
Scanner in =new Scanner(System. in );
int t = in.nextInt();
for (int i = 0; i < t; i++) {
BigInteger a = in.nextBigInteger();
BigInteger b = in.nextBigInteger();
for (BigInteger j = a; j.compareTo(b) < -1; j.add(BigInteger.ONE)) {
BigInteger n = j;
BigInteger r = new BigInteger("2");
int wow = n.intValue();
BigInteger y = r.pow(wow - 1);
System.out.println(y);
if ((y.mod(n)).compareTo(BigInteger.ONE) == 0)
System.out.println(j);
}
}
}
現在不顯示任何輸出。
在for
循環中,您不會遞增j
。
for (BigInteger j = a; j.compareTo(b)<-1;
j.add(BigInteger.ONE)) {
j.add(...)
不會更改j
,而是返回一個新的BigInteger
。
要修復您的代碼,只需將j.add(BigInteger.ONE)
的結果分配給j
:
for (BigInteger j = a; j.compareTo(b)<-1;
j = j.add(BigInteger.ONE)) {
底線:請在將代碼發布到StackOverflow之前嘗試對其進行調試。
使用您選擇的IDE。
會發生這種錯誤,但是如果您調試代碼並輕而易舉地逐步執行程序,直到您想知道為什么它還沒有推進,它們就很容易被緩存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.