Problem : Given a number, determine if it is prime or not.
      
To determine if a given number is prime or not, you have to check if the given number is divisible by any number other than 1 and itself. If it is, then it is not a prime number. 
* In this algorithm, we check if the given number is less than or equal to zero. If it is then it is not a prime number. 
* Next we check to see if the given number is 2.  2 is the only even prime number. 
* Then we check if the given number is even. If it is, then it is not a prime number. 
* Lastly we divide the given number starting from 3 till the square root of the given number. 
  /**
     * This method checks if the given number n is a prime number or not.
     *
     * @param n - The number to be checked.
     * @return boolean
     */
    public static boolean isPrime(int n)
    {
        if (n <= 1)
        {
            return false;
        }
        if (n == 2)
        {
            return true;
        }
        if (n % 2 == 0)
        {
            return false;
        }
        int m = (int) Math.sqrt(n);
        for (int i = 3; i <= m; i += 2)
        {
            if (n % i == 0)
            {
                return false;
            }
        }
        return true;
    }
This algorithm has a time complexity of O ( n ) and a space complexity of O ( 1 ).
============================================
Problem : Given an integer n, generate all the prime numbers till n.
This solution uses the isPrime discussed above. 
* In this solution we first create an array of boolean of size n + 1 and fill the array with true. 
* We then know that zero and one are not prime numbers. Hence we mark the first 2 entries to be false.
* Next we start with 2 and then set all multiples of 2 less than the given number to false. At this point, 2 is a prime number and all multiples of 2 are marked false.
This is repeated in a loop with increments of 1 till we hit a number lesser than the square root of the given number. So at the end of the second iteration, 3 will be true indicating it is prime and all of it's multiples are marked false and so on.
  /**
     * This generates the prime numbers using Sieve of Eratosthenes.
     * @param n
     */
    public static void generatePrime(int n)
    {
        boolean[] isPrime = new boolean[n+1];
        Arrays.fill(isPrime, true);
        isPrime[0] = false;
        isPrime[1] = false;
        for (int i = 2; i <= (int) Math.sqrt(n); i++)
        {
            if (isPrime[i])
            {
                for (int j = i * i; j <= n; j += i)
                {
                    isPrime[j] = false;
                }
            }
        }
        System.out.println("Prime numbers till " + n + " are : \n");
        for (int i = 0; i <>
        {
            if (isPrime[i])
            {
                System.out.println(i);
            }
        }
    }
Comments