2019-05-09 19:32:54 +08:00
|
|
|
package Others;
|
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
/** @author Varun Upadhyay (https://github.com/varunu28) */
|
2017-09-29 02:38:20 +08:00
|
|
|
public class SieveOfEratosthenes {
|
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
/**
|
|
|
|
* This method implements the Sieve of Eratosthenes Algorithm
|
|
|
|
*
|
|
|
|
* @param n The number till which we have to check for prime Prints all the prime numbers till n
|
|
|
|
*/
|
|
|
|
public static void findPrimesTillN(int n) {
|
|
|
|
int[] arr = new int[n + 1];
|
2017-09-29 02:38:20 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
for (int i = 0; i <= n; i++) {
|
|
|
|
arr[i] = 1;
|
|
|
|
}
|
2017-09-29 02:38:20 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
arr[0] = arr[1] = 0;
|
2017-09-29 02:38:20 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
for (int i = 2; i <= Math.sqrt(n); i++) {
|
|
|
|
if (arr[i] == 1) {
|
|
|
|
for (int j = 2; i * j <= n; j++) {
|
|
|
|
arr[i * j] = 0;
|
2017-09-29 02:38:20 +08:00
|
|
|
}
|
2020-10-24 18:23:28 +08:00
|
|
|
}
|
|
|
|
}
|
2017-09-29 02:38:20 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
for (int i = 0; i < n + 1; i++) {
|
|
|
|
if (arr[i] == 1) {
|
|
|
|
System.out.print(i + " ");
|
|
|
|
}
|
2017-09-29 02:38:20 +08:00
|
|
|
}
|
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
System.out.println();
|
|
|
|
}
|
2017-09-29 02:38:20 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
// Driver Program
|
|
|
|
public static void main(String[] args) {
|
|
|
|
int n = 100;
|
2017-09-29 02:38:20 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
// Prints 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
|
|
|
|
findPrimesTillN(n);
|
|
|
|
}
|
2017-09-29 02:38:20 +08:00
|
|
|
}
|