Here, first we understand that what is prime number,
Prime Numbers
A prime number is a natural number greater than 1, that is divisible by only two numbers: 1 and itself.
For Example: 2, 3, 5, 7,11,13……..are the prime numbers.
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.
Problem:
Input : Enter a number: 17
Output: 17 is a prime number.
Explanation
This Java program checks if a given number is prime or not. It prompts the user for input, then utilizes a `for` loop to iterate from 2 up to the square root of the number. Within each iteration, it checks if the number is divisible by the current value of `i`. If a divisor is found, it concludes the number is not prime. If no divisors are found, then it’s a prime number.
Solution:
code:
class PrimeNo{ public static void main(String []args){ int num=7; int temp=0; for(int i =2;i<=num-1;i++){ if(num%i==0){ temp=temp+1; } } if(temp==0){ System.out.println(num+" is a prime number"); } else{ System.out.println(num+" is not prime number "); } } }
Output:
7 is a prime number
Approach 2 : By Using Scanner Class :
import java.util.Scanner; // import scanner class class PrimeNo{ public static void main(String []args){ Scanner sc =new Scanner(System.in); // object of scanner class int temp=0; System.out.println("enter any number"); int num = sc.nextInt(); for(int i =2;i<=num-1;i++){ if(num%i==0){ temp=temp+1; } } if(temp==0){ System.out.println(num+" is a prime number"); } else{ System.out.println(num+" is not prime number "); } } }
Output:
enter any number 77 77 is not prime number
more java programs for practice:
Java Program to Get Input from User
Find the Greatest of the Two Numbers in Java
Addition of two numbers in java