forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp021.java
More file actions
47 lines (36 loc) · 919 Bytes
/
p021.java
File metadata and controls
47 lines (36 loc) · 919 Bytes
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
/*
* Solution to Project Euler problem 21
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p021 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p021().run());
}
/*
* We find the sum of proper divisors of a number by brute force,
* and apply the definition of an amicable number straightforwardly.
*/
public String run() {
int sum = 0;
for (int i = 1; i < 10000; i++) {
if (isAmicable(i))
sum += i;
}
return Integer.toString(sum);
}
private static boolean isAmicable(int n) {
int m = divisorSum(n);
return m != n && divisorSum(m) == n;
}
private static int divisorSum(int n) {
int sum = 0;
for (int i = 1; i < n; i++) {
if (n % i == 0)
sum += i;
}
return sum;
}
}