当前位置:网站首页>Xiao Lan does experiments (count the number of primes)

Xiao Lan does experiments (count the number of primes)

2022-06-21 15:37:00 iFulling

【 Problem description 】

Xiao Lan likes scientific research very much , He recently made an experiment and got a batch of experimental data , That's twomillion positive integers . If as expected , All the experimental data x All should be satisfied 1 0 7 ≤ x ≤ 1 0 8 10^7 ≤ x ≤ 10^8 107x108. But there will be some errors when doing experiments , It will lead to some unexpected data , This error data y The range is 1 0 3 ≤ y ≤ 1 0 12 10^3 ≤ y ≤ 10^{12} 103y1012 . Because Xiao Lan is very reliable in doing experiments , So of all his experimental data 99.99% All the above are in line with expectations . All the experimental data of Xiaolan are in primes.txt in , Now he wants to count how many of the twomillion positive integers are prime numbers , Can you tell him ?

【 material 】

Baidu network disk link : primes.txt
Extraction code : imfa

【 Problem solving 】

The theorem is used here : If a number is a composite number , Then its minimum prime factor must be less than or equal to its square root .

【 Code 】

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class B {
    
    public static void main(String[] args) throws IOException {
    
        int count = 0;
        BufferedReader reader = new BufferedReader(new FileReader("src/primes.txt"));
        String line = null;
        while ((line = reader.readLine()) != null) {
    
            long num = Long.parseLong(line);
            if (check(num)) {
    
                System.out.println(num);
                count++;
            }
        }
        reader.close();
        System.out.println(count);
    }

    public static boolean check(double nums) {
    
        /* *  Judge whether it is a prime number  * */
        boolean ret = true;
        for (int i = 2; i <= (int) (Math.pow(nums, 0.5) + 1); i++) {
    
            if (nums % i == 0) {
    
                ret = false;
                break;
            }
        }
        return ret;
    }
}
原网站

版权声明
本文为[iFulling]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211239296173.html