- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathAmicableNumber.java
71 lines (65 loc) · 2.35 KB
/
AmicableNumber.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
67
68
69
70
71
packagecom.thealgorithms.maths;
importjava.util.LinkedHashSet;
importjava.util.Set;
importorg.apache.commons.lang3.tuple.Pair;
/**
* Amicable numbers are two different natural numbers that the sum of the
* proper divisors of each is equal to the other number.
* (A proper divisor of a number is a positive factor of that number other than the number itself.
* For example, the proper divisors of 6 are 1, 2, and 3.)
* A pair of amicable numbers constitutes an aliquot sequence of period 2.
* It is unknown if there are infinitely many pairs of amicable numbers.
*
* <p>
* link: https://en.wikipedia.org/wiki/Amicable_numbers
* <p>
* Simple Example: (220, 284)
* 220 is divisible by {1,2,4,5,10,11,20,22,44,55,110} <-SUM = 284
* 284 is divisible by {1,2,4,71,142} <-SUM = 220.
*/
publicfinalclassAmicableNumber {
privateAmicableNumber() {
}
/**
* Finds all the amicable numbers in a given range.
*
* @param from range start value
* @param to range end value (inclusive)
* @return list with amicable numbers found in given range.
*/
publicstaticSet<Pair<Integer, Integer>> findAllInRange(intfrom, intto) {
if (from <= 0 || to <= 0 || to < from) {
thrownewIllegalArgumentException("Given range of values is invalid!");
}
Set<Pair<Integer, Integer>> result = newLinkedHashSet<>();
for (inti = from; i < to; i++) {
for (intj = i + 1; j <= to; j++) {
if (isAmicableNumber(i, j)) {
result.add(Pair.of(i, j));
}
}
}
returnresult;
}
/**
* Checks whether 2 numbers are AmicableNumbers or not.
*/
publicstaticbooleanisAmicableNumber(inta, intb) {
if (a <= 0 || b <= 0) {
thrownewIllegalArgumentException("Input numbers must be natural!");
}
returnsumOfDividers(a, a) == b && sumOfDividers(b, b) == a;
}
/**
* Recursively calculates the sum of all dividers for a given number excluding the divider itself.
*/
privatestaticintsumOfDividers(intnumber, intdivisor) {
if (divisor == 1) {
return0;
} elseif (number % --divisor == 0) {
returnsumOfDividers(number, divisor) + divisor;
} else {
returnsumOfDividers(number, divisor);
}
}
}