In this tutorial, we’ll explore a Java Program to Display Prime Numbers up to a given range.
A prime number is a natural number greater than 1 that has no divisors other than 1 and itself. Examples include: 2, 3, 5, 7, 11, 13, 17….
Efficient Prime Check Logic
To check if a number is prime or not you don't need to run a loop starting from 2 till that number to check if number has any divisor. You can use a more efficient approach to loop only up to \( \sqrt{n}\) (square root of the number).If no divisor is found in this range, the number is prime.
Let's try to understand why looping only up to \( \sqrt{n}\) is sufficient.
If a number n is not prime, it can be expressed as a product of two factors-
\( n=a\times b\)
At least one of these factors must be less than or equal to \( \sqrt{n}\).
For example, for n = 36, factors are (6 × 6) or (4 × 9). Notice that one factor (4 or 6) is = \( \sqrt{36}\) = 6. Therefore, if no divisor is found up to \( \sqrt{n}\), there cannot be any divisor beyond \( \sqrt{n}\) either, because the corresponding smaller factor would already have been detected.
Looking for more efficient way to display prime numbers. Refer these sieving algorithms- Java Program - Sieve of Eratosthenes to Find Prime Numbers, Java Program - Sieve of Sundaram to Find Prime Numbers
Java program to print prime numbers
import java.util.Scanner;
public class PrintPrime {
public static void main(String[] args) {
// take input from the user
Scanner sc = new Scanner(System.in);
System.out.println("Enter number till which prime numbers are to be printed: ");
int num = sc.nextInt();
for(int i = 2; i <= num; i++){
if(isPrime(i)){
System.out.print(i + " ");
}
}
sc.close();
}
// Method to check if the passed number
// is prime or not
private static boolean isPrime(int num){
if (num <= 1) return false;
boolean flag = true;
// loop from 2, increment it till number/2
for(int i = 2; i <= Math.sqrt(num); i++){
// no remainder, means divides
if(num % i == 0){
flag = false;
break;
}
}
return flag;
}
}
Output
Enter number till which prime numbers are to be printed: 50 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Here scanner class is used to get input from the user.
Refer How to read input from console in Java to see other ways to get input from user.
That's all for this topic Java Program to Display Prime Numbers. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment