Java Program – Check Prime Number
In this tutorial, we shall check if a number is prime or not.
You can use either while loop statement or for loop statement to find whether the given number is prime number or not.
Algorithm
- Start.
- Read a number
N
from user. - Initialize
i
with 2. - If
i
is less thanN/i
, continue with next step, else go to step 7. - Check if
i
is a factor ofN
. Ifi
is a factor ofN
,N
is not prime, return false. Go to step 8. - If
i
is not a factor, incrementi
. Go to step 4. - Return
true
. - End.
ADVERTISEMENT
Java Program
In the following program, we shall write a function isPrime(), using the above algorithm. This function takes a number as argument, then check if the number is prime or not, and returns a boolean value. The function returns true if the number is prime, else it returns false.
Example.java
/** * Java Program - Check if Number is Prime Number */ public class Example { public static void main(String[] args) { System.out.println("Is 32 prime : "+isPrime(32)); System.out.println("Is 41 prime : "+isPrime(41)); } public static boolean isPrime(int num) { for(int i = 2; i <= num/i; ++i) { if(num % i == 0) { return false; } } return true; } }
Run the above program, and you shall get the following output in the console.
Output
Is 32 prime : false Is 41 prime : true
Conclusion
In this Java Tutorial, we learned how to write a Java Program to check if a given number is prime of not.