package algorithm;
import java.io.*;
/**
* @author: xyz
* @create: 2022/8/13
* @Description:
* @FileName: Exercise22_10
* @History:
* @自定义内容:
*/
public class Exercise22_10 {
public static void main(String[] args) throws IOException {
final long SIZE = 10_000_000_000L;
int count = 0;
File file = new File("D:\\IDEA程序\\JavaFXProject\\src\\files\\PrimeNumbers.dat");
if (file.exists()) file.delete();
for (int i = 10; i <= SIZE; i *= 10) {
int start = i / 10 + 1;
count += primeNumber(start, i, file);
System.out.println(String.format("%,d: %,d", i, count));
}
}
/** 返回start~end之间素数个数,file表示存储素数文件 */
public static int primeNumber(int start, int end, File file) throws IOException {
int squareRoot = 1; //平方根
int number = start, count = 0;
while (number <= end) { //查找范围内的素数
boolean isPrime = true;
while (squareRoot * squareRoot < number) squareRoot++; //查找小于number的最大平方根
try(DataOutputStream outputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file, true)));
DataInputStream inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)))) {
try {
int value; //如果不是素数,能够被小于等于自己平方根的素数整除
for (int i = 0; i < file.length() / 4 && (value = inputStream.readInt()) <= squareRoot; i++) {
if (number != value && number % value == 0) {
isPrime = false;
break;
}
}
if (isPrime) { //素数
outputStream.writeInt(number);
count++;
}
} catch (EOFException ex) {}
}
number++;
}
return count;
}
}