-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #411 from jash-kothari/sieves-algo
Sieves Algorithm for prime number generation till n
- Loading branch information
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
Program's_Contributed_By_Contributors/Java_Programs/PrimeNumbers.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import java.util.*; | ||
import java.lang.*; | ||
import java.io.*; | ||
|
||
// Using the sieve of Eratosthenes | ||
public class PrimeNumbers { | ||
public static List<Integer> calcPrimeNumbers(int n) { | ||
boolean[] isPrimeNumber = new boolean[n + 1]; // boolean defaults to | ||
// false | ||
List<Integer> primes = new ArrayList<Integer>(); | ||
for (int i = 2; i < n; i++) { | ||
isPrimeNumber[i] = true; | ||
} | ||
for (int i = 2; i < n; i++) { | ||
if (isPrimeNumber[i]) { | ||
primes.add(i); | ||
// now mark the multiple of i as non-prime number | ||
for (int j = i; j * i <= n; j++) { | ||
isPrimeNumber[i * j] = false; | ||
} | ||
} | ||
|
||
} | ||
|
||
return primes; | ||
} | ||
|
||
public static void main(String[] args) { | ||
Scanner sc=new Scanner(System.in); | ||
System.out.println("Enter the value of n"); | ||
int n=sc.nextInt(); | ||
List<Integer> calcPrimeNumbers = calcPrimeNumbers(n); | ||
for (Integer integer : calcPrimeNumbers) { | ||
System.out.println(integer); | ||
} | ||
} | ||
} |