Write a Java program to check whether a given number is prime or not – Java Tutorial
Problem Statement
Write a Java program to check whether a given number is prime or not
Solution:
A number is said to be a prime number if it is divisible by itself or by 1reverse is equal to the original number.
For example,
The number 13 is a prime number, as it is divisible by itself and by 1.
The number 12 is not a prime number as it is divisible by itself, 1 and also 2, 3, 4, and 6. Hence 12 is not a prime number
Video Tutorial:
Step to write the prime number program in Java.
First, create a class named PrimeNo and add the main method to it.
Next, set the value of the flag to 0 indicating a number is a prime number.
Read the number to be checked whether prime or not from the user using an object of scanner class object.
Check whether the number is divisible by any other except itself or 1. If the number is divisible by any other number except itself or 1, then set the value of the flag to 1 and break the loop.
If the value of the flag is equal to 0 then print, the number is a prime number, or print the number is not a prime number using the statement System.out.println
/* * Write a Java Program to check whether the given number is prime or not * * Subscribe to Mahesh Huddar YouTube Channel for more Videos */ import java.util.Scanner; public class PrimeNo { public static void main(String args[]) { int n, flag = 0; Scanner in = new Scanner(System.in); System.out.println("Enter the no:"); n = in.nextInt(); for (int i = 2; i < n; i++) { if (n%i==0) { flag = 1; break; } } if (flag == 1) { System.out.println(n+ " is not a prime number"); } else { System.out.println(n+ " is a prime number"); } } }
The output of the Prime Number Program in Java
Case 1:
Enter a number: 13
13 is a prime number
Case 2:
Enter a number: 121
121 is not a prime number
Summary:
In this article, we understood How to write a Java program to check whether a given number is prime or not – Java Tutorial. If you like the tutorial share it with your friends. Like the Facebook page for regular updates and the YouTube channel for video tutorials.