Skip to content

Commit 74b7426

Browse files
MickonamamickonamarealDuYuanChao
authored
Solution to Euler Project Problem03 (TheAlgorithms#2069)
* Solution to Euler Project Problem03 * Solution to Euler Project Problem03 format fix * format code * update prime function Co-authored-by: mickonama <[email protected]> Co-authored-by: shellhub <[email protected]>
1 parent 95484f8 commit 74b7426

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

ProjectEuler/Problem03.java

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

0 commit comments

Comments
 (0)