|
1 | 1 | import java.util.Arrays; |
| 2 | +import java.util.HashMap; |
| 3 | +import java.util.Map; |
2 | 4 |
|
3 | 5 | public class Exercise8_5 { |
4 | | - |
5 | | - public static void sieve(int n) { |
6 | | - int[] start = new int[n]; |
7 | | - boolean[] bool = new boolean[n]; |
8 | | - for (int i = 0; i < start.length; i++) { |
9 | | - start[i] = i; |
10 | | - } |
11 | | - for (int i = 0; i < bool.length; i++) { |
12 | | - if (start[i] == i * i) { |
13 | | - bool[i] = false; |
14 | | - } else { |
| 6 | + |
| 7 | + public static void sieve(int limit) { |
| 8 | + |
| 9 | + int[] nums = new int[limit]; |
| 10 | + for (int i = 0; i < nums.length; i++) { |
| 11 | + nums[i] = i; |
| 12 | + } |
| 13 | + System.out.println(Arrays.toString(nums)); |
| 14 | + |
| 15 | + boolean[] bool = new boolean[limit]; |
| 16 | + for (int i = 2; i < bool.length; i++) { |
15 | 17 | bool[i] = true; |
16 | 18 | } |
17 | | - } |
| 19 | + |
| 20 | + // Mark all composite numbers |
| 21 | + for (int i = 2; i < (bool.length / 2); i++) { |
| 22 | + if (bool[i]) { |
| 23 | +// bool[i] = false; |
| 24 | + int multiple = 2; |
| 25 | + while (i * multiple < bool.length) { |
| 26 | + bool [i * multiple] = false; |
| 27 | + multiple++; |
| 28 | + } |
| 29 | + } |
| 30 | + } |
18 | 31 |
|
19 | | - System.out.println(Arrays.toString(start)); |
20 | | - System.out.println(Arrays.toString(bool)); |
21 | | - } |
| 32 | + |
| 33 | + Map myMap = new HashMap(bool.length); |
| 34 | + for (int i = 0; i < nums.length; i++) { |
| 35 | + myMap.put(nums[i], bool[i]); |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | + System.out.println(Arrays.toString(bool)); |
| 40 | + System.out.println(myMap); |
| 41 | + } |
22 | 42 |
|
23 | 43 | public static void main(String[] args) { |
24 | 44 | sieve(120); |
|
0 commit comments