Array: Prime Numbers less than 50

Question: Write a program that gives the first 50 prime numbers using the following approach: Check whether any of the prime numbers less than or equal to i can divide i evenly. If not, n is prime.

Output:

package Array;

/**
 * Q: Write a program which gives the first 50 prime numbers using the following approach:
 * Check whether any of the prime numbers less than or equal to n can divide n
 * evenly. If not, n is prime.
 * Created by aarushi on 13/5/21.
 */
public class Ch7Ex6 {

    //max size of the array of primeNumbers
    final static int SIZE= 50;

    public static void main (String [] args){
        //create the array that will store the prime numbers
        int [] primeNumbers= new int[SIZE];
        //variable that stores the number of elements in primeNumbers array
        int primeElementsCount=0;
        
        for (int i=2; i<50; i++){
            //initially assume that the number is a prime number
            boolean isPrime= true;
            //run a loop through the primeNumbers array
            for (int j=0; j<primeElementsCount; j++){
                //Check whether any of the prime numbers less than 
                //or equal to i can divide i evenly.
                if (i%primeNumbers[j]==0){
                    isPrime=false;
                }
            }

            if(isPrime){
                primeNumbers[primeElementsCount++]=i;
            }
        }

        //display the array
        for(int i=0; i<primeElementsCount; i++){
            System.out.print(primeNumbers[i]+ " ");
        }
    }
}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: