public class PrimeNumberExample {
public static void main(String args[]) {
//get input till which prime number to be printed
System.out.println("Enter the number till which prime number to be printed: ");
int limit = new Scanner(System.in).nextInt();
System.out.println("Printing prime number from 1 to " + limit);
for(int number = 2; number<=limit; number++){
//print prime numbers only
if(isPrime(number)){
System.out.println(number);
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false; //number is divisible so its not prime
}
}
return true; //number is prime now
}
}
Output:
Enter the number till which prime number to be printed:
20
Printing prime number from 1 to 20
2
3
5
7
11
13
17
19
public static void main(String args[]) {
//get input till which prime number to be printed
System.out.println("Enter the number till which prime number to be printed: ");
int limit = new Scanner(System.in).nextInt();
System.out.println("Printing prime number from 1 to " + limit);
for(int number = 2; number<=limit; number++){
//print prime numbers only
if(isPrime(number)){
System.out.println(number);
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false; //number is divisible so its not prime
}
}
return true; //number is prime now
}
}
Output:
Enter the number till which prime number to be printed:
20
Printing prime number from 1 to 20
2
3
5
7
11
13
17
19
Read More