可以用java实现吗
时间: 2023-09-16 16:08:53 浏览: 37
可以用Java实现上述算法。以下是一个Java代码示例:
```java
import java.math.BigInteger;
public class PrimitiveRoot {
public static void main(String[] args) {
BigInteger p = new BigInteger("1000000007"); // 要计算的素数
BigInteger q = p.subtract(BigInteger.ONE).divide(new BigInteger("2")); // 计算 q
BigInteger r = new BigInteger("2"); // 初始化 r
BigInteger g = null; // 原根
boolean found = false;
while (!found) {
// 计算 g^q mod p
BigInteger temp = r.modPow(q, p);
if (!temp.equals(BigInteger.ONE)) {
// 如果 g^q mod p 不等于 1,则 r 是一个原根
g = r;
found = true;
}
r = r.add(BigInteger.ONE);
}
System.out.println("Primitive root of " + p + " is " + g);
}
}
```
该代码使用了 BigInteger 类来处理大整数运算。需要注意的是,对于非常大的素数,计算其原根可能需要很长时间,因此需要耐心等待程序运行完成。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)