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 numb
| 20 | * 284 is divisible by {1,2,4,71,142} <-SUM = 220. |
| 21 | */ |
| 22 | public final class AmicableNumber { |
| 23 | private AmicableNumber() { |
| 24 | } |
| 25 | /** |
| 26 | * Finds all the amicable numbers in a given range. |
| 27 | * |
| 28 | * @param from range start value |
| 29 | * @param to range end value (inclusive) |
| 30 | * @return list with amicable numbers found in given range. |
| 31 | */ |
| 32 | public static Set<Pair<Integer, Integer>> findAllInRange(int from, int to) { |
| 33 | if (from <= 0 || to <= 0 || to < from) { |
| 34 | throw new IllegalArgumentException("Given range of values is invalid!"); |
| 35 | } |
| 36 | |
| 37 | Set<Pair<Integer, Integer>> result = new LinkedHashSet<>(); |
| 38 | |
| 39 | for (int i = from; i < to; i++) { |
| 40 | for (int j = i + 1; j <= to; j++) { |
| 41 | if (isAmicableNumber(i, j)) { |
| 42 | result.add(Pair.of(i, j)); |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | return result; |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Checks whether 2 numbers are AmicableNumbers or not. |
| 51 | */ |
| 52 | public static boolean isAmicableNumber(int a, int b) { |
| 53 | if (a <= 0 || b <= 0) { |
| 54 | throw new IllegalArgumentException("Input numbers must be natural!"); |
| 55 | } |
| 56 | return sumOfDividers(a, a) == b && sumOfDividers(b, b) == a; |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Recursively calculates the sum of all dividers for a given number excluding the divider itself. |
| 61 | */ |
| 62 | private static int sumOfDividers(int number, int divisor) { |
| 63 | if (divisor == 1) { |
| 64 | return 0; |
| 65 | } else if (number % --divisor == 0) { |
| 66 | return sumOfDividers(number, divisor) + divisor; |
| 67 | } else { |
| 68 | return sumOfDividers(number, divisor); |
| 69 | } |
| 70 | } |
| 71 | } |
nothing calls this directly
no outgoing calls
no test coverage detected