Site icon

Check whether given integer number is prime or not in java (example)

1. Check given integer number is prime or not in java (Loop from 2 to n – 1)

private static boolean checkPrime(int number) {

	for (int range = 2; range < number ; range++ ) {
		
		if(number % range == 0)
			return false;
	}
	return true;
}

2. Check given integer number is prime or not in java (Loop from 2 to n/2)

private static boolean checkPrimeLoopTillHalf(int number) {

	for (int range = 2; range <= number / 2; range++ ) {
		
		if(number % range == 0)
			return false;
	}
	return true;
}

3. Check given integer number is prime or not in java (Loop from 2 to sqrt(n))

private static boolean checkPrimeLoopTillSqrt(int number) {

	int sqrt = (int) Math.sqrt(number);
	for (int range = 2; range <= sqrt; range++ ) {
		
		if(number % range == 0)
			return false;
	}
	return true;
}

Program: check given integer number is prime or not in java (example)

package org.learn;

import java.util.Scanner;

public class CheckPrimeNumber {

	private static boolean checkPrime(int number) {

		for (int range = 2; range < number ; range++ ) {
			
			if(number % range == 0)
				return false;
		}
		return true;
	}
	
	private static boolean checkPrimeLoopTillHalf(int number) {

		for (int range = 2; range <= number / 2; range++ ) {
			
			if(number % range == 0)
				return false;
		}
		return true;
	}
	
	private static boolean checkPrimeLoopTillSqrt(int number) {

		int sqrt = (int) Math.sqrt(number);
		for (int range = 2; range <= sqrt; range++ ) {
			
			if(number % range == 0)
				return false;
		}
		return true;
	}

	public static void main(String[] args) {
		try (Scanner scanner = new Scanner(System.in)) {
			System.out.printf("1. Enter input number : ");
			int inputNumber = scanner.nextInt();
			
			if(inputNumber < 2) {
				System.out.println("Enter number greater than 1");
				return;
			}
			
			boolean isPrime = checkPrime(inputNumber);
			System.out.printf("2. Is prime number : %b", isPrime);
			
			isPrime = checkPrimeLoopTillHalf(inputNumber);
			System.out.printf("\n3. Is prime number - Loop till number/2: %b", isPrime);
			
			isPrime = checkPrimeLoopTillSqrt(inputNumber);
			System.out.printf("\n4. Is prime number - Loop till sqrt(number): %b", isPrime);
		}
	}
}

Output: check given integer number is prime or not in java

1. Enter input number : 4
2. Is prime number : false
3. Is prime number - Loop till number/2: false
4. Is prime number - Loop till sqrt(number): false

1. Enter input number : 7
2. Is prime number : true
3. Is prime number - Loop till number/2: true
4. Is prime number - Loop till sqrt(number): true

1. Enter input number : 12
2. Is prime number : false
3. Is prime number - Loop till number/2: false
4. Is prime number - Loop till sqrt(number): false
Exit mobile version