Skip to content

Commit b294ddc

Browse files
Add AliquotSum (TheAlgorithms#3765)
1 parent 9cde140 commit b294ddc

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/main/java/com/thealgorithms/maths/AliquotSum.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,35 @@ public static int getAliquotValue(int number) {
3030

3131
return sumWrapper.value;
3232
}
33+
34+
/**
35+
* Function to calculate the aliquot sum of an integer number
36+
*
37+
* @param n a positive integer
38+
* @return aliquot sum of given {@code number}
39+
*/
40+
public static int getAliquotSum(int n) {
41+
if (n <= 0)
42+
return -1;
43+
int sum = 1;
44+
double root = Math.sqrt(n);
45+
/*
46+
* We can get the factors after the root by dividing number by its factors
47+
* before the root.
48+
* Ex- Factors of 100 are 1, 2, 4, 5, 10, 20, 25, 50 and 100.
49+
* Root of 100 is 10. So factors before 10 are 1, 2, 4 and 5.
50+
* Now by dividing 100 by each factor before 10 we get:
51+
* 100/1 = 100, 100/2 = 50, 100/4 = 25 and 100/5 = 20
52+
* So we get 100, 50, 25 and 20 which are factors of 100 after 10
53+
*/
54+
for (int i = 2; i <= root; i++) {
55+
if (n % i == 0) {
56+
sum += i + n / i;
57+
}
58+
}
59+
// if n is a perfect square then its root was added twice in above loop, so subtracting root from sum
60+
if (root == (int) root)
61+
sum -= root;
62+
return sum;
63+
}
3364
}

src/test/java/com/thealgorithms/maths/AliquotSumTest.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,9 @@ void testGetMaxValue() {
1212
assertEquals(6, AliquotSum.getAliquotValue(6));
1313
assertEquals(9, AliquotSum.getAliquotValue(15));
1414
assertEquals(1, AliquotSum.getAliquotValue(19));
15+
assertEquals(0, AliquotSum.getAliquotSum(1));
16+
assertEquals(6, AliquotSum.getAliquotSum(6));
17+
assertEquals(9, AliquotSum.getAliquotSum(15));
18+
assertEquals(1, AliquotSum.getAliquotSum(19));
1519
}
1620
}

0 commit comments

Comments
 (0)