Pages

Content of this Website is not optimized for Mobile📵. It is recommended that the Website be viewed on a Laptop💻 or Desktop🖳🖥.

How to check whether a number is prime or not? in Java - Interview Coding Question

 Question: Write a program to find whether a number is prime or not? 

SlidesFind whether a number is prime or not? | Java Interview Coding Questions | Kings Classes

Answer:  A prime number is a natural number greater than 1 which is divisible by only 1 and itself. So, if any number is divisible by any other number, it is not a prime number. 

For example 2, 3, 5, 7, 11…  are prime numbers because they can neither be divided nor is a result of the multiplication.

Note: 0 and 1 are not prime numbers. The 2 is the only even prime number because all the other even numbers can be divided by 2.


Note: Prime numbers cannot be arranged into rectangles but Composite numbers can.

Algorithm/Solution:
  1. Get the integer number from the user as an input (x).
  2. Divide the number x with (2 to x/2).
  3. If x is divisible by any value (2 to x/2) it is not prime.
  4. Else it is prime.
Here, note that we are dividing the number x from 2 to x/2. It is because a number is not divisible by more than its half.

Below is the Java Program to find whether a number is prime or not? 
package com.kingsclasses.primenumber;

import java.util.Scanner;

/**
 * @author Raja Bhaiya Vishwakarma 
 * Program to check whether a given number is prime or not.
 */
public class PrimeNumberExample {

	public static void main(String[] args) {

		// 1. Get the integer number from the user as an input (x).
		int x;
		Scanner scanner = new Scanner(System.in);
		System.out.print("Enter any number (x): ");
		x = scanner.nextInt();
		scanner.close();
		
		// 2. Divide the number x with (2 to x/2).
		boolean flag = false;
		for (int i = 2; i <= x / 2; i++) {
			// Condition for non-prime number.
			if (x % i == 0) {
				flag = true;
				break;
			}
		}
		
		if(flag){
			// 3. If x is divisible by any value (2 to x/2) it is not prime.
			System.out.println(x + " is not a prime number.");
		} else {
			// 4. Else it is prime.
			System.out.println(x + " is a prime number.");
		}
	}
}
Output:
Enter any number (x) : 5
5 is a prime number.
Enter any number (x) : 6
6 is not a prime number.

Try the above code with below java editor:

No comments:

Post a Comment

Kings Classes: Quick Links!