How to check if number is a prime in Java

To check if number is a prime in Java you can use the following snippet.

Sample Java

public static boolean IsPrime(long input) {
	boolean primeCheck = true;
	for (long count = 3; count <= Math.sqrt(input); count += 2)
		if (input % count == 0) {
			primeCheck = false;
			break;
		}
	if (( input%2 !=0 && primeCheck && input > 2) || input == 2) {
		return true;
	} else {
		return false;
	}
}

Please Share us:
Please rate this snippet

One thought on “How to check if number is a prime in Java

Leave a Reply