Add AliquotSum (#3765)

This commit is contained in:
Taranjeet Singh Kalsi 2022-11-12 01:27:18 +05:30 committed by GitHub
parent 9cde14095c
commit b294ddcb38
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 0 deletions

View File

@ -30,4 +30,35 @@ public class AliquotSum {
return sumWrapper.value;
}
/**
* Function to calculate the aliquot sum of an integer number
*
* @param n a positive integer
* @return aliquot sum of given {@code number}
*/
public static int getAliquotSum(int n) {
if (n <= 0)
return -1;
int sum = 1;
double root = Math.sqrt(n);
/*
* We can get the factors after the root by dividing number by its factors
* before the root.
* Ex- Factors of 100 are 1, 2, 4, 5, 10, 20, 25, 50 and 100.
* Root of 100 is 10. So factors before 10 are 1, 2, 4 and 5.
* Now by dividing 100 by each factor before 10 we get:
* 100/1 = 100, 100/2 = 50, 100/4 = 25 and 100/5 = 20
* So we get 100, 50, 25 and 20 which are factors of 100 after 10
*/
for (int i = 2; i <= root; i++) {
if (n % i == 0) {
sum += i + n / i;
}
}
// if n is a perfect square then its root was added twice in above loop, so subtracting root from sum
if (root == (int) root)
sum -= root;
return sum;
}
}

View File

@ -12,5 +12,9 @@ public class AliquotSumTest {
assertEquals(6, AliquotSum.getAliquotValue(6));
assertEquals(9, AliquotSum.getAliquotValue(15));
assertEquals(1, AliquotSum.getAliquotValue(19));
assertEquals(0, AliquotSum.getAliquotSum(1));
assertEquals(6, AliquotSum.getAliquotSum(6));
assertEquals(9, AliquotSum.getAliquotSum(15));
assertEquals(1, AliquotSum.getAliquotSum(19));
}
}