Java program that prints prime numbers between 1 to n?

Java

1 answer

Answer

1142847

2026-04-24 14:05

+ Follow

The easiest way is to use a prime sieve (google Sieve of Eratosthenes).

Here is pseudo-code for the algorithm.

- create a boolean array of size n

- for every true index 2 through n

- - keep the index as true, mark all multiples of the index as false.

So, for example, if n=10

start with 2, keep 2 true. Mark 4,6,8,10 as false.

next is 3, keep it true. mark 6,9 as false (6 was already false).

next is 4, it is false, skip it.

next is 5, keep it true. mark 10 as false (it was already false).

6 is false, skip it

7 is true, keep it true. the next multiple of 7 is greater than 10

8,9, 10 are all false.

you are done - the values marked true (1,2, 3,5,7) are your primes.

ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.