|
| 1 | +// version 1 |
| 2 | +public class Primes { |
| 3 | + |
| 4 | + public static void main(String[] args) { |
| 5 | + int max = 10; |
| 6 | + for (int x = 2; x <= max; x++) { |
| 7 | + boolean isPrime = true; |
| 8 | + for (int y = 2; y < x; y++) |
| 9 | + if (x % y == 0) |
| 10 | + isPrime = false; |
| 11 | + if (isPrime) |
| 12 | + System.out.println(x); |
| 13 | + } |
| 14 | + } |
| 15 | +} |
| 16 | +-------------------------------------------- |
| 17 | +// version 2: break |
| 18 | +public class Primes { |
| 19 | + |
| 20 | + public static void main(String[] args) { |
| 21 | + int max = 10; |
| 22 | + for (int x = 2; x <= max; x++) { |
| 23 | + boolean isPrime = true; |
| 24 | + for (int y = 2; y < x; y++) |
| 25 | + if (x % y == 0) { |
| 26 | + isPrime = false; |
| 27 | + break; |
| 28 | + } |
| 29 | + if (isPrime) |
| 30 | + System.out.println(x); |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | +-------------------------------------------- |
| 35 | +// version 3: break, add to list |
| 36 | +import java.util.ArrayList; |
| 37 | + |
| 38 | +public class Primes { |
| 39 | + |
| 40 | + public static void main(String[] args) { |
| 41 | + ArrayList<Integer> primeList = new ArrayList<>(); |
| 42 | + |
| 43 | + int max = 10000; |
| 44 | + for (int x = 2; x <= max; x++) { |
| 45 | + boolean isPrime = true; |
| 46 | + for (int y = 2; y < x; y++) |
| 47 | + if (x % y == 0) { |
| 48 | + isPrime = false; |
| 49 | + break; |
| 50 | + } |
| 51 | + if (isPrime) |
| 52 | + primeList.add(x); |
| 53 | + } |
| 54 | + System.out.println(primeList); |
| 55 | + } |
| 56 | +} |
| 57 | +-------------------------------------------- |
| 58 | +// version 4: break, add to list, square root |
| 59 | +import java.util.ArrayList; |
| 60 | + |
| 61 | +public class Primes { |
| 62 | + |
| 63 | + public static void main(String[] args) { |
| 64 | + ArrayList<Integer> primeList = new ArrayList<>(); |
| 65 | + |
| 66 | + int max = 200000; |
| 67 | + for (int x = 2; x <= max; x++) { |
| 68 | + boolean isPrime = true; |
| 69 | + for (int y = 2; y < Math.sqrt(x); y++) |
| 70 | + if (x % y == 0) { |
| 71 | + isPrime = false; |
| 72 | + break; |
| 73 | + } |
| 74 | + if (isPrime) |
| 75 | + primeList.add(x); |
| 76 | + } |
| 77 | + System.out.println(primeList); |
| 78 | + } |
| 79 | +} |
0 commit comments