代码有错误
时间: 2024-02-25 17:58:16 浏览: 17
非常抱歉,代码确实存在错误。在计算 q 的时候,应该计算 p-1 的值,而不是 p。另外,在判断 g 是否为原根的时候,应该遍历 q 的所有质因数,而不是 p-1 的所有质因数。以下是修改后的代码:
```java
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class AllPrimitiveRoots {
public static void main(String[] args) {
BigInteger p = new BigInteger("1000000007"); // 要计算的素数
BigInteger q = p.subtract(BigInteger.ONE); // 计算 q
List<BigInteger> factors = primeFactors(q); // 计算 q 的质因数
BigInteger g = new BigInteger("2"); // 初始化 g
while (true) {
boolean isPrimitiveRoot = true;
for (BigInteger factor : factors) {
// 计算 g^(q/factor) mod p
BigInteger temp = g.modPow(q.divide(factor), p);
if (temp.equals(BigInteger.ONE)) {
// 如果 g^(q/factor) mod p 等于 1,则 g 不是一个原根
isPrimitiveRoot = false;
break;
}
}
if (isPrimitiveRoot) {
System.out.println(g + " is a primitive root of " + p);
}
g = g.add(BigInteger.ONE);
if (g.compareTo(p) >= 0) {
break;
}
}
}
// 计算一个大整数的质因数
private static List<BigInteger> primeFactors(BigInteger n) {
List<BigInteger> factors = new ArrayList<>();
BigInteger i = BigInteger.valueOf(2);
while (i.multiply(i).compareTo(n) <= 0) {
if (n.mod(i).equals(BigInteger.ZERO)) {
factors.add(i);
n = n.divide(i);
} else {
i = i.add(BigInteger.ONE);
}
}
if (n.compareTo(BigInteger.ONE) > 0) {
factors.add(n);
}
return factors;
}
}
```
感谢您的指正,希望这次能够帮助到您!