Print prime numbers in Java OR Check whether the Entered number is prime or not.
import java.util.Scanner;
public class PrimeNumber{
public static void listPrimeNumbers(int input){
for(int j=2;j<=input;j++){
checkPrimeNumber(j);
}
}
public static void checkPrimeNumber(int enteredNumber){
int count=0;
for(int i=2;i<=enteredNumber;i++){
if(enteredNumber%i==0){
count++;
}
}
/*if(count>=2){
System.out.println(enteredNumber+ " is not a prime number.");
}else
{
System.out.println(enteredNumber+ " is prime number");
}*/
if(count<2 p=""> System.out.println(enteredNumber);
}
}
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number:");
int number=sc.nextInt();
listPrimeNumbers(number);
}
}
output: Enter the number 11
2
3
5
7
11
Note: I have created two methods, either you list the prime numbers based on your input or you can check whether the entered number is prime or not. If un comment the section under checkPrimeNumber() method.
2>
public class PrimeNumber{
public static void listPrimeNumbers(int input){
for(int j=2;j<=input;j++){
checkPrimeNumber(j);
}
}
public static void checkPrimeNumber(int enteredNumber){
int count=0;
for(int i=2;i<=enteredNumber;i++){
if(enteredNumber%i==0){
count++;
}
}
/*if(count>=2){
System.out.println(enteredNumber+ " is not a prime number.");
}else
{
System.out.println(enteredNumber+ " is prime number");
}*/
if(count<2 p=""> System.out.println(enteredNumber);
}
}
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number:");
int number=sc.nextInt();
listPrimeNumbers(number);
}
}
output: Enter the number 11
2
3
5
7
11
Note: I have created two methods, either you list the prime numbers based on your input or you can check whether the entered number is prime or not. If un comment the section under checkPrimeNumber() method.
2>
Comments
Post a Comment