Printing out Prime Numbers from 2 to 1000

后端 未结 5 721
萌比男神i
萌比男神i 2020-12-21 19:01

I am writing a code that write all the prime numbers from 2 to 1000 in a file, named primes.txt. For some reason I am not able to figure out the correct way to do this probl

5条回答
  •  庸人自扰
    2020-12-21 19:39

    calculation can be made even faster by checking the division with prime numbers only. Any non prime number is divisible by some prime number smaller than itself.

        static List primes = new ArrayList();
    
    public static void main(String[] args) {
        for (int i = 2; i < 10000; i++) {
            if(checkPrime(i)){
                primes.add(i);
            }
        }
        System.out.println(primes);
    }
    
    private static boolean checkPrime(int n) {
        for (Integer i : primes) {
            if(i*i > n ){
                break;
            }else if(n%i==0 )
                return false;
         }
        return true;
    }
    

提交回复
热议问题