TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
lcm_sum.cpp
Go to the documentation of this file.
1
14
15
#include <cassert>
16
#include <cstdint>
17
#include <iostream>
18
#include <vector>
19
24
namespace
math
{
30
uint64_t
lcmSum
(
const
uint16_t& num) {
31
uint64_t i = 0, j = 0;
32
std::vector<uint64_t> eulerTotient(num + 1);
33
std::vector<uint64_t> sumOfEulerTotient(num + 1);
34
35
// storing initial values in eulerTotient vector
36
for
(i = 1; i <= num; i++) {
37
eulerTotient[i] = i;
38
}
39
40
// applying totient sieve
41
for
(i = 2; i <= num; i++) {
42
if
(eulerTotient[i] == i) {
43
for
(j = i; j <= num; j += i) {
44
eulerTotient[j] = eulerTotient[j] / i;
45
eulerTotient[j] = eulerTotient[j] * (i - 1);
46
}
47
}
48
}
49
50
// computing sum of euler totients
51
for
(i = 1; i <= num; i++) {
52
for
(j = i; j <= num; j += i) {
53
sumOfEulerTotient[j] += eulerTotient[i] * i;
54
}
55
}
56
57
return
((sumOfEulerTotient[num] + 1) * num) / 2;
58
}
59
}
// namespace math
60
66
static
void
test
() {
67
uint64_t n = 2;
68
uint64_t test_1 =
math::lcmSum
(n);
69
assert(test_1 == 4);
70
std::cout <<
"Passed Test 1!"
<< std::endl;
71
72
n = 5;
73
uint64_t test_2 =
math::lcmSum
(n);
74
assert(test_2 == 55);
75
std::cout <<
"Passed Test 2!"
<< std::endl;
76
77
n = 10;
78
uint64_t test_3 =
math::lcmSum
(n);
79
assert(test_3 == 320);
80
std::cout <<
"Passed Test 3!"
<< std::endl;
81
82
n = 11;
83
uint64_t test_4 =
math::lcmSum
(n);
84
assert(test_4 == 616);
85
std::cout <<
"Passed Test 4!"
<< std::endl;
86
87
n = 15;
88
uint64_t test_5 =
math::lcmSum
(n);
89
assert(test_5 == 1110);
90
std::cout <<
"Passed Test 5!"
<< std::endl;
91
}
92
97
int
main
() {
98
test
();
// execute the tests
99
return
0;
100
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
math
for assert
math::lcmSum
uint64_t lcmSum(const uint16_t &num)
Definition
lcm_sum.cpp:30
math
lcm_sum.cpp
Generated by
1.18.0