-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
aliquot_sum.cpp
77 lines (68 loc) · 1.64 KB
/
aliquot_sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* @file
* @brief Program to return the [Aliquot
* Sum](https://en.wikipedia.org/wiki/Aliquot_sum) of a number
*
* @details
* The Aliquot sum \f$s(n)\f$ of a non-negative integer n is the sum of all
* proper divisors of n, that is, all the divisors of n, other than itself.
*
* Formula:
*
* \f[
* s(n) = \sum_{d|n, d\neq n}d.
* \f]
*
* For example;
* \f$s(18) = 1 + 2 + 3 + 6 + 9 = 21 \f$
*
* @author [SpiderMath](https://github.com/SpiderMath)
*/
#include <cassert> /// for assert
#include <cstdint>
#include <iostream> /// for IO operations
/**
* @brief Mathematical algorithms
* @namespace math
*/
namespace math {
/**
* @brief to return the aliquot sum of a number
* @param num The input number
*/
uint64_t aliquot_sum(const uint64_t num) {
if (num == 0 || num == 1) {
return 0; // The aliquot sum for 0 and 1 is 0
}
uint64_t sum = 0;
for (uint64_t i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
return sum;
}
} // namespace math
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
// Aliquot sum of 10 is 1 + 2 + 5 = 8
assert(math::aliquot_sum(10) == 8);
// Aliquot sum of 15 is 1 + 3 + 5 = 9
assert(math::aliquot_sum(15) == 9);
// Aliquot sum of 1 is 0
assert(math::aliquot_sum(1) == 0);
// Aliquot sum of 97 is 1 (the aliquot sum of a prime number is 1)
assert(math::aliquot_sum(97) == 1);
std::cout << "All the tests have successfully passed!\n";
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run the self-test implementations
return 0;
}