Skip to content

Commit 9f7613b

Browse files
authored
Code refactor for AliquotSum improvements (TheAlgorithms#3027)
Fix TheAlgorithms#3026
1 parent 4b15b2c commit 9f7613b

File tree

2 files changed

+30
-16
lines changed

2 files changed

+30
-16
lines changed
Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.thealgorithms.maths;
22

3+
import java.util.stream.IntStream;
4+
35
/**
46
* In number theory, the aliquot sum s(n) of a positive integer n is the sum of
57
* all proper divisors of n, that is, all divisors of n other than n itself. For
@@ -9,26 +11,22 @@
911
*/
1012
public class AliquotSum {
1113

12-
public static void main(String[] args) {
13-
assert aliquotSum(1) == 0;
14-
assert aliquotSum(6) == 6;
15-
assert aliquotSum(15) == 9;
16-
assert aliquotSum(19) == 1;
17-
}
18-
1914
/**
20-
* Finds the aliquot sum of an integer number
15+
* Finds the aliquot sum of an integer number.
2116
*
2217
* @param number a positive integer
2318
* @return aliquot sum of given {@code number}
2419
*/
25-
public static int aliquotSum(int number) {
26-
int sum = 0;
27-
for (int i = 1, limit = number / 2; i <= limit; ++i) {
28-
if (number % i == 0) {
29-
sum += i;
30-
}
31-
}
32-
return sum;
20+
public static int getAliquotValue(int number) {
21+
var sumWrapper = new Object() {
22+
int value = 0;
23+
};
24+
25+
IntStream.iterate(1, i -> ++i)
26+
.limit(number / 2)
27+
.filter(i -> number % i == 0)
28+
.forEach(i -> sumWrapper.value += i);
29+
30+
return sumWrapper.value;
3331
}
3432
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.thealgorithms.maths;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
7+
public class AliquotSumTest {
8+
9+
@Test
10+
void testGetMaxValue() {
11+
assertEquals(0, AliquotSum.getAliquotValue(1));
12+
assertEquals(6, AliquotSum.getAliquotValue(6));
13+
assertEquals(9, AliquotSum.getAliquotValue(15));
14+
assertEquals(1, AliquotSum.getAliquotValue(19));
15+
}
16+
}

0 commit comments

Comments
 (0)