Sunday, January 29, 2023

Print Prime Number Program in java with Explanation using different ways

 Here are three different ways to print prime numbers in Java:

1)Using a for loop and a nested if statement:

Explanation: The outer loop starts from 2 and goes up to n. For each value of i, we use a nested for loop to check if i is divisible by any number between 2 and i-1. If i is divisible by any number, it is not a prime number and we set isPrime to false. If isPrime is still true after the inner loop, we print i as a prime number.

2)Using a for loop and the sqrt function:


Explanation: This program is similar to the first one, but it uses the Math.sqrt function to find the square root of i. By checking divisibility only up to the square root of i, we can reduce the number of iterations in the inner loop, making the program more efficient.

3) Using the Sieve of Eratosthenes algorithm:


Explanation: The Sieve of Eratosthenes is a well-known algorithm for finding all prime numbers up to a given limit. The program starts by creating an array of n + 1 boolean values and setting all values to true. Then, it uses two nested for loops to mark all multiples.

0 comments:

If you have any doubts,please let me know