Prime Number Example Java Program


Definition

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number (i.e. 1, 2, 3, 4, 5, 6, etc.) is called a prime number (or a prime) if it has exactly two positive divisors, 1 and the number itself. Natural numbers greater than 1 that are not prime are called composite. The number 12 is not a prime, as 12 items can be placed into 3 equal-size columns of 4 each (among other ways). 11 items cannot be all placed into several equal-size columns of more than 1 item each without some extra items leftover (a remainder). Therefore, the number 11 is a prime. Among the numbers 1 to 6, the numbers 2, 3, and 5 are the prime numbers, while 1, 4, and 6 are not prime.

Prime Number Example Program

import java.util.*;
 
class PrimeNumber{
	public static void main(String args[]){
		int num1, status = 1, num2 = 3;
		Scanner input = new Scanner(System.in);
		System.out.println("How many prime numbers do you need?");
		num1 = input.nextInt();
		if (num1 >= 1){
			System.out.println("First "+num1+" prime numbers are");
			System.out.println(2);
		}
		for ( int i = 2 ; i <=num1 ;  ){
			for ( int j = 2 ; j <= Math.sqrt(num2) ; j++ ){
				if ( num2%j == 0 ){
					status = 0;
					break;
				}
			}
			if ( status != 0 ){
				System.out.println(num2);
				i++;
			}
			status = 1;
			num2++;
		}         
	}
}

Sample Output

Output is:
How many prime numbers do you need?
9
First 9 prime numbers are
2
3
5
7
11
13
17
19
23