MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / AliquotSum

Class AliquotSum

src/main/java/com/thealgorithms/maths/AliquotSum.java:12–63  ·  view source on GitHub ↗

In number theory, the aliquot sum s(n) of a positive integer n is the sum of all proper divisors of n, that is, all divisors of n other than n itself. For example, the proper divisors of 15 (that is, the positive divisors of 15 that are not equal to 15) are 1, 3 and 5, so the aliquot sum of 15 is 9

Source from the content-addressed store, hash-verified

10 * 3 + 5). Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum
11 */
12public final class AliquotSum {
13 private AliquotSum() {
14 }
15
16 /**
17 * Finds the aliquot sum of an integer number.
18 *
19 * @param number a positive integer
20 * @return aliquot sum of given {@code number}
21 */
22 public static int getAliquotValue(int number) {
23 var sumWrapper = new Object() { int value = 0; };
24
25 IntStream.iterate(1, i -> ++i).limit(number / 2).filter(i -> number % i == 0).forEach(i -> sumWrapper.value += i);
26
27 return sumWrapper.value;
28 }
29
30 /**
31 * Function to calculate the aliquot sum of an integer number
32 *
33 * @param n a positive integer
34 * @return aliquot sum of given {@code number}
35 */
36 public static int getAliquotSum(int n) {
37 if (n <= 0) {
38 return -1;
39 }
40 int sum = 1;
41 double root = Math.sqrt(n);
42 /*
43 * We can get the factors after the root by dividing number by its factors
44 * before the root.
45 * Ex- Factors of 100 are 1, 2, 4, 5, 10, 20, 25, 50 and 100.
46 * Root of 100 is 10. So factors before 10 are 1, 2, 4 and 5.
47 * Now by dividing 100 by each factor before 10 we get:
48 * 100/1 = 100, 100/2 = 50, 100/4 = 25 and 100/5 = 20
49 * So we get 100, 50, 25 and 20 which are factors of 100 after 10
50 */
51 for (int i = 2; i <= root; i++) {
52 if (n % i == 0) {
53 sum += i + n / i;
54 }
55 }
56 // if n is a perfect square then its root was added twice in above loop, so subtracting root
57 // from sum
58 if (root == (int) root) {
59 sum -= (int) root;
60 }
61 return sum;
62 }
63}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected