java编程实现以下功能:输入两个正整数,将这两个正整数之间的所有素数写入文件pNumber.txt
时间: 2024-03-22 09:38:03 浏览: 71
好的,以下是Java代码实现:
```java
import java.io.FileWriter;
import java.io.IOException;
public class PrimeNumberWriter {
public static void main(String[] args) {
int start = 2; // 起始数
int end = 100; // 结束数
String fileName = "pNumber.txt"; // 文件名
try {
FileWriter fileWriter = new FileWriter(fileName);
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
fileWriter.write(i + "\n"); // 写入文件
}
}
fileWriter.close();
System.out.println("已将素数写入文件:" + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
// 判断是否是素数
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
```
你可以将起始数和结束数修改为你需要的正整数,然后运行程序即可在当前目录下生成 `pNumber.txt` 文件,并将两个正整数之间的所有素数写入该文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)