|
8 | 8 | * <p>Link: https://projecteuler.net/problem=3
|
9 | 9 | */
|
10 | 10 | public class Problem03 {
|
11 |
| - /** |
12 |
| - * Check if a given number is prime |
13 |
| - * |
14 |
| - * @param n integer number |
15 |
| - * @return true if n is prime, false otherwise |
16 |
| - */ |
17 |
| - static boolean isPrime(int n) { |
18 |
| - for (int i = 2; i <= Math.sqrt(n); i++) { |
19 |
| - if (n % i == 0) |
20 |
| - return false; |
21 |
| - } |
22 |
| - return true; |
| 11 | + /** |
| 12 | + * Check if a given number is prime |
| 13 | + * |
| 14 | + * @param n integer number |
| 15 | + * @return true if n is prime, false otherwise |
| 16 | + */ |
| 17 | + static boolean isPrime(int n) { |
| 18 | + for (int i = 2; i <= Math.sqrt(n); i++) { |
| 19 | + if (n % i == 0) return false; |
23 | 20 | }
|
| 21 | + return true; |
| 22 | + } |
24 | 23 |
|
25 |
| - /** |
26 |
| - * Calculate all the prime factors of a number and return the largest |
27 |
| - * |
28 |
| - * @param n integer number |
29 |
| - * @return the maximum prime factor of the given number |
30 |
| - */ |
31 |
| - static long maxPrimeFactor(long n) { |
32 |
| - for (int i = 2; i < n / 2; i++) { |
33 |
| - if (isPrime(i)) |
34 |
| - while (n % i == 0) { |
35 |
| - n /= i; |
36 |
| - } |
| 24 | + /** |
| 25 | + * Calculate all the prime factors of a number and return the largest |
| 26 | + * |
| 27 | + * @param n integer number |
| 28 | + * @return the maximum prime factor of the given number |
| 29 | + */ |
| 30 | + static long maxPrimeFactor(long n) { |
| 31 | + for (int i = 2; i < n / 2; i++) { |
| 32 | + if (isPrime(i)) |
| 33 | + while (n % i == 0) { |
| 34 | + n /= i; |
37 | 35 | }
|
38 |
| - return n; |
39 | 36 | }
|
| 37 | + return n; |
| 38 | + } |
40 | 39 |
|
41 |
| - public static void main(String[] args) { |
42 |
| - long c = 600851475143L; |
43 |
| - int[][] testNumbers = { |
44 |
| - {87, 29}, |
45 |
| - {10, 5}, |
46 |
| - {21, 7}, |
47 |
| - {657, 73}, |
48 |
| - {777, 37} |
49 |
| - }; |
50 |
| - for (int[] num : testNumbers) { |
51 |
| - assert Problem03.maxPrimeFactor(num[0]) == num[1]; |
52 |
| - } |
53 |
| - assert Problem03.maxPrimeFactor(c) == 6857; |
| 40 | + public static void main(String[] args) { |
| 41 | + long c = 600851475143L; |
| 42 | + int[][] testNumbers = { |
| 43 | + {87, 29}, |
| 44 | + {10, 5}, |
| 45 | + {21, 7}, |
| 46 | + {657, 73}, |
| 47 | + {777, 37} |
| 48 | + }; |
| 49 | + for (int[] num : testNumbers) { |
| 50 | + assert Problem03.maxPrimeFactor(num[0]) == num[1]; |
54 | 51 | }
|
| 52 | + assert Problem03.maxPrimeFactor(c) == 6857; |
| 53 | + } |
55 | 54 | }
|
0 commit comments