Prime Numbers in Java - Algorithms

前端 未结 6 882
南笙
南笙 2021-01-22 15:48

I have started learning to code in Java and decided I would use the Project Euler site to give me little tasks to try and complete with each bit of new coding I learn. So I came

6条回答
  •  醉梦人生
    2021-01-22 16:34

    This is java version of this:

     static boolean isPrime(int n){
        if (n == 2) return true;
        if (n == 3) return true;
        if (n % 2 == 0) return false;
        if (n % 3 == 0) return false;
    
        int i = 5;
        int w = 2;
        while (i * i <= n) {
            if(n % i == 0)
            return false;
    
            i += w;
            w = 6 - w;
        }
        return true;
    }
    

    As it is described by @Alexandru: It's a variant of the classic O(sqrt(N)) algorithm. It uses the fact that a prime (except 2 and 3) is of form 6k-1 and 6k+1 and looks only at divisors of this form.

提交回复
热议问题