|
| 1 | +package com.thealgorithms.maths; |
| 2 | + |
| 3 | +/** |
| 4 | + * In number theory, an abundant number or excessive number is a positive integer for which |
| 5 | + * the sum of its proper divisors is greater than the number. |
| 6 | + * Equivalently, it is a number for which the sum of proper divisors (or aliquot sum) is greater than n. |
| 7 | + * |
| 8 | + * The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16. |
| 9 | + * |
| 10 | + * Wiki: https://en.wikipedia.org/wiki/Abundant_number |
| 11 | + */ |
| 12 | +public final class AbundantNumber { |
| 13 | + |
| 14 | + private AbundantNumber() { |
| 15 | + } |
| 16 | + |
| 17 | + // Function to calculate sum of all divisors including n |
| 18 | + private static int sumOfDivisors(int n) { |
| 19 | + int sum = 1 + n; // 1 and n are always divisors |
| 20 | + for (int i = 2; i <= n / 2; i++) { |
| 21 | + if (n % i == 0) { |
| 22 | + sum += i; // adding divisor to sum |
| 23 | + } |
| 24 | + } |
| 25 | + return sum; |
| 26 | + } |
| 27 | + |
| 28 | + // Common validation method |
| 29 | + private static void validatePositiveNumber(int number) { |
| 30 | + if (number <= 0) { |
| 31 | + throw new IllegalArgumentException("Number must be positive."); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Check if {@code number} is an Abundant number or not by checking sum of divisors > 2n |
| 37 | + * |
| 38 | + * @param number the number |
| 39 | + * @return {@code true} if {@code number} is an Abundant number, otherwise false |
| 40 | + */ |
| 41 | + public static boolean isAbundant(int number) { |
| 42 | + validatePositiveNumber(number); |
| 43 | + |
| 44 | + return sumOfDivisors(number) > 2 * number; |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Check if {@code number} is an Abundant number or not by checking Aliquot Sum > n |
| 49 | + * |
| 50 | + * @param number the number |
| 51 | + * @return {@code true} if {@code number} is a Abundant number, otherwise false |
| 52 | + */ |
| 53 | + public static boolean isAbundantNumber(int number) { |
| 54 | + validatePositiveNumber(number); |
| 55 | + |
| 56 | + return AliquotSum.getAliquotSum(number) > number; |
| 57 | + } |
| 58 | +} |
0 commit comments