我正在尝试解决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。
会发生这种错误,但是如果您调试代码并轻而易举地逐步执行程序,直到您想知道为什么它还没有推进,它们就很容易被缓存。

关于java - 如何在JAVA中为(2 ^(n-1)mod 1 = 1)保留更大的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57812900/

10-10 18:32