July 08, 2024

JaiHoDevs

Check Given Number Is a Prime Number or Not Java Program

Write a program to check the given number is a prime number or not?

Description:

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number. For example, 5 is prime, as only 1 and 5 divide it, whereas 6 is composite, since it has the divisors 2 and 3 in addition to 1 and 6. The fundamental theorem of arithmetic establishes the central role of primes in number theory: any integer greater than 1 can be expressed as a product of primes that is unique up to ordering. This theorem requires excluding 1 as a prime.

Code:

package com.java2novice.algos;

public class MyPrimeNumCheck {

    public boolean isPrimeNumber(int number){
        
        for(int i=2; i<=number/2; i++){
            if(number % i == 0){
                return false;
            }
        }
        return true;
    }
    
    public static void main(String a[]){
        MyPrimeNumCheck mpc = new MyPrimeNumCheck();
        System.out.println("Is 17 prime number? "+mpc.isPrimeNumber(17));
        System.out.println("Is 19 prime number? "+mpc.isPrimeNumber(19));
        System.out.println("Is 15 prime number? "+mpc.isPrimeNumber(15));
    }
}

Output:

Is 17 prime number? true
Is 19 prime number? true
Is 15 prime number? false

Here's a simple Java program to check if a given number is a prime number:

import java.util.Scanner;


public class PrimeCheck {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int number = scanner.nextInt();

        scanner.close();


        if (isPrime(number)) {

            System.out.println(number + " is a prime number.");

        } else {

            System.out.println(number + " is not a prime number.");

        }

    }


    public static boolean isPrime(int number) {

        if (number <= 1) {

            return false;

        }

        for (int i = 2; i <= Math.sqrt(number); i++) {

            if (number % i == 0) {

                return false;

            }

        }

        return true;

    }

}

Explanation:

  1. Import Scanner: The program uses the Scanner class to get input from the user.
  2. Get Input: The user is prompted to enter a number.
  3. isPrime Method: This method checks if a number is prime:
    • Numbers less than or equal to 1 are not prime.
    • The loop runs from 2 to the square root of the number. If the number is divisible by any of these, it is not prime.
  4. Output: Based on the result from isPrime, the program prints whether the number is prime or not.

You can compile and run this program to check if a given number is a prime number.

Subscribe to get more Posts :