forked from yesiamrajeev/Hacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSieve-Algorithm.java
More file actions
54 lines (36 loc) · 1.23 KB
/
Sieve-Algorithm.java
File metadata and controls
54 lines (36 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
code :-
import java.util.Scanner;
public class SieveOfEratosthenes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the limit (n): ");
int n = sc.nextInt();
sc.close();
boolean[] isPrime = new boolean[n + 1];
// Initialize all numbers as prime
for (int i = 2; i <= n; i++) {
isPrime[i] = true;
}
// Sieve algorithm
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false; // Mark multiples as non-prime
}
}
}
// Print prime numbers
System.out.println("Prime numbers up to " + n + ":");
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
System.out.print(i + " ");
}
}
}
}
How it works:
1. Start with an array isPrime initialized to true for all numbers ≥ 2.
2. For each number i starting from 2, mark all multiples of i as false (not prime).
3. Continue until i*i > n.
4. Remaining true indices are prime numbers.
✅ This is efficient with a time complexity of O(n log l )