Skip to content

Commit 8c5ec65

Browse files
* add AliquotSum
* add Median
1 parent 35ccbd9 commit 8c5ec65

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

Maths/AliquotSum.java

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package Maths;
2+
3+
/**
4+
* <p>
5+
* In number theory, the aliquot sum s(n) of a positive integer n is the sum of all proper divisors of n,
6+
* that is, all divisors of n other than n itself.
7+
* For example, the proper divisors of 15 (that is, the positive divisors of 15 that are not equal to 15)
8+
* are 1, 3 and 5, so the aliquot sum of 15 is 9 i.e. (1 + 3 + 5).
9+
* </p>
10+
* Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum
11+
*/
12+
public class AliquotSum {
13+
public static void main(String[] args) {
14+
assert aliquotSum(1) == 0;
15+
assert aliquotSum(6) == 6;
16+
assert aliquotSum(15) == 9;
17+
assert aliquotSum(19) == 1;
18+
}
19+
20+
/**
21+
* Finds the aliquot sum of an integer number
22+
*
23+
* @param number a positive integer
24+
* @return aliquot sum of given {@code number}
25+
*/
26+
public static int aliquotSum(int number) {
27+
int sum = 0;
28+
for (int i = 1; i < number; ++i) {
29+
if (number % i == 0) {
30+
sum += i;
31+
}
32+
}
33+
return sum;
34+
}
35+
}

Maths/Median.java

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package Maths;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Wikipedia: https://en.wikipedia.org/wiki/Median
7+
*/
8+
public class Median {
9+
public static void main(String[] args) {
10+
assert median(new int[]{0}) == 0;
11+
assert median(new int[]{1, 2}) == 1.5;
12+
assert median(new int[]{4, 1, 3, 2}) == 2.5;
13+
assert median(new int[]{1, 3, 3, 6, 7, 8, 9}) == 6;
14+
assert median(new int[]{1, 2, 3, 4, 5, 6, 8, 9}) == 4.5;
15+
}
16+
17+
/**
18+
* Calculate average median
19+
*
20+
* @param values number series
21+
* @return median of given {@code values}
22+
*/
23+
public static double median(int[] values) {
24+
Arrays.sort(values);
25+
int length = values.length;
26+
return length % 2 == 0 ? (values[length / 2] + values[length / 2 - 1]) / 2.0 : values[length / 2];
27+
}
28+
}

0 commit comments

Comments
 (0)