Prime number java means the number has divisible by 1 and itself. Writing a Prime number program in java is very easy. In the following program of java prime number we taken as a user defined input. For calculating the prime numbers in java we required a math function. Prime number program in java is easy to implement. To find prime numbers in java we apply for loop logic with the counter to increase the number.
Java program to find prime numbers is given as spoon feed below. From this you can easily calculate the prime numbers in java how much you have to calculate.
Program for find prime number java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.util.*; // exception handling in java example class PrimeNumbers { public static void main(String args[]) { int a, status = 1, num = 3; Scanner in = new Scanner(System.in); // logic of user input for prime numbers in java System.out.println("Enter the number of prime numbers you want"); a = in.nextInt(); if (a >= 1) { System.out.println("First "+a+" prime numbers are :-"); System.out.println(2); } for ( int count = 2 ; count <=a ; ) // logic of prime number java { for ( int j = 2 ; j <= Math.sqrt(num) ; j++ ) { if ( num%j == 0 ) { status = 0; break; } } if ( status != 0 ) { System.out.println(num); count++; } status = 1; num++; } } } // End of java program to find prime number |
Output of prime number program in java