DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Mik Seljamaa πŸ‡ͺπŸ‡ͺ
Mik Seljamaa πŸ‡ͺπŸ‡ͺ

Posted on

Prime Number

not a decent check

public static boolean isPrime(int number){

    for (int divisor = 2; divisor <= (number/2); divisor++){
        if (number % divisor == 0){
            return false; 
        }
    }

    return true;
}
Enter fullscreen mode Exit fullscreen mode

R. Sedgewick and K. Wayne trix

public class PrimeSieve {
    public static void main(String[] args) { 
        int n = Integer.parseInt(args[0]);

        boolean[] isPrime = new boolean[n+1];
        for (int i = 2; i <= n; i++) {
            isPrime[i] = true;
        }
        for (int factor = 2; factor*factor <= n; factor++) {
            if (isPrime[factor]) {
                for (int j = factor; factor*j <= n; j++) {
                    isPrime[factor*j] = false;
                }
            }
        }
        int primes = 0;
        for (int i = 2; i <= n; i++) {
            if (isPrime[i]) primes++;
        }
        System.out.println("The number of primes <= " + n + " is " + primes);
    }
}
Enter fullscreen mode Exit fullscreen mode

Copyright Β© 2000–2011, Robert Sedgewick and Kevin Wayne.
Last updated: Tue Aug 30 09:58:33 EDT 2016.

Top comments (1)

Collapse
 
lytecyde profile image
Mik Seljamaa πŸ‡ͺπŸ‡ͺ

I just wrote this up so i might remember it if I ever had to turn up on an interview... lolz

Why You Need to Study Javascript Fundamentals

The harsh reality for JS Developers: If you don't study the fundamentals, you'll be just another β€œCoder”. Top learnings on how to get to the mid/senior level faster as a JavaScript developer by Dragos Nedelcu.