I will be using the Sieve of Eratosthenes algorithm as mentioned on the wiki.
The code is like this:
The code is like this:
import java.util.Arrays; import java.util.Scanner; public class FindingPrime { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = Integer.parseInt(scanner.nextLine()); boolean[] a = new boolean[n]; Arrays.fill(a, true); int squareRoot = (int) Math.ceil(Math.sqrt(n)); for (int i = 2; i < squareRoot; i++) { if (a[i]) { int square = i * i; for (int j = square; j < n; j = (j + i)) { a[j] = false; } } } for (int i = 2; i < a.length; i++) { if (a[i]) { System.out.print(i + " "); } } } }
Comments
Post a Comment