-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem21.java
66 lines (58 loc) · 1.35 KB
/
Problem21.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.javamultiplex.projecteuler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
*
* @author Rohit Agarwal
* @category Project Euler Problems
* @Problem 21 - Amicable numbers
*
*/
public class Problem21 {
public static void main(String[] args) {
int target = 10000;
List<Integer> list = new ArrayList<>();
int b = 0, c = 0, sum = 0;
for (int a = 2; a <= target; a++) {
if (!list.contains(a)) {
b = sumOfDivisors(a);
if (a != b) {
c = sumOfDivisors(b);
if (c == a) {
list.add(b);
list.add(a);
}
}
}
}
int size = list.size();
for (int i = 0; i < size; i++) {
sum += list.get(i);
}
System.out.println("The sum of all the amicable numbers under 10000 is :" + sum);
}
private static int sumOfDivisors(int num) {
List<Integer> list = new ArrayList<>();
int limit = (int) Math.sqrt(num);
int temp = 0;
int sum = 0;
// Getting divisors and adding into List.
for (int i = 1; i <= limit; i++) {
if (num % i == 0) {
list.add(i);
temp = num / i;
if (i != temp) {
list.add(temp);
}
}
}
// Sorting List in acceding order.
Collections.sort(list);
int size = list.size();
for (int i = 0; i < size - 1; i++) {
sum += list.get(i);
}
return sum;
}
}