write a programe in java to check the input number is prime number or not
Answers
CODE :-
import java.util.Scanner; \\ importing the package
class prime \\ declaring the class
{
public static void main(String args[]) \\declaring the main()method
{
System.out.println("Enter a no."); \\ Asking the user to input a no.
Scanner sc=new Scanner(System.in); \\ input variable creation
int c=0, i, a; \\ declaring the variables
a = sc.nextInt();
for (i=1;i<=a;i++)
{
if(a%i==0)
c++;
}
if(c==2)
{
System.out.println("Prime");
}
else
{
System.out.println("Not prime")
}
}
}
Explanation
A prime number has 2 factors (i.e. 1 and the number itself).
Therefore, we used one for-loop and one if else statement to count the number of factors.
And if the no. of count (c in the code) is 2, then the entered no. is prime otherwise it is not a prime no.
Glossary
Variable ║ Type ║ Description
a ║ int ║ To store the number
i ║ int ║ To run the loop
c ║ int ║ To store the no. of count
Dry Run
a ║ i ║ c
7 ║ 1 ║ 0,1
║ 2 ║ 1
║ 3 ║ 1
║ 4 ║ 1
║ 5 ║ 1
║ 6 ║ 1
║ 7 ║ 2