Skip to content

Latest commit

 

History

History
51 lines (41 loc) · 1.16 KB

2023-12-26-check-if-number-is-prime.md

File metadata and controls

51 lines (41 loc) · 1.16 KB
layout title author categories toc description
post
Java Program To Check If The Given Number is Prime or Not
gaurav
Java Programs
Core Java
true
In this tutorial, we will see a Java program to check if the given number is Prime or Not.

In this tutorial, we will see a Java program to check if the given number is prime or not.

What is a Prime Number?

A number that can be divided exactly only by itself and 1.

For example 7, 17 and 41.

Java Program To Check If The Given Number is Binary Or Not

public class PrimeNumber {

    public static void main(String[] args) {
        int num = 41;
        boolean isPrimeNumber = isPrime(num);
        if (isPrimeNumber) {
            System.out.println(num + " is a prime number.");
        } else {
            System.out.println(num + " is not a prime number.");
        }
    }

    public static boolean isPrime(int num) {
        if (num <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Output

41 is a prime number.