Java、素数的个数

 

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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值