@@ -29,8 +29,7 @@ A way of thinking about it is the following:
29
29
* If there are two distinct prime divisors $n = p_1^{e_1} \cdot p_2^{e_2}$, then you can arrange all divisors in form of a tabular.
30
30
31
31
$$ \begin{array}{c|ccccc}
32
- & 1 & p_2 & p_2^2 & \dots & p_2^{e_2} \\\\
33
- \hline
32
+ & 1 & p_2 & p_2^2 & \dots & p_2^{e_2} \\\\\hline
34
33
1 & 1 & p_2 & p_2^2 & \dots & p_2^{e_2} \\\\
35
34
p_1 & p_1 & p_1 \cdot p_2 & p_1 \cdot p_2^2 & \dots & p_1 \cdot p_2^{e_2} \\\\
36
35
p_1^2 & p_1^2 & p_1^2 \cdot p_2 & p_1^2 \cdot p_2^2 & \dots & p_1^2 \cdot p_2^{e_2} \\\\
@@ -42,18 +41,39 @@ So the number of divisors is trivially $(e_1 + 1) \cdot (e_2 + 1)$.
42
41
43
42
* A similar argument can be made if there are more then two distinct prime factors.
44
43
44
+
45
+ ``` cpp
46
+ long long numberOfDivisors (long long num) {
47
+ long long total = 1;
48
+ for (int i = 2; (long long)i * i <= num; i++) {
49
+ if (num % i == 0) {
50
+ int e = 0;
51
+ do {
52
+ e++;
53
+ num /= i;
54
+ } while (num % i == 0);
55
+ total * = e + 1;
56
+ }
57
+ }
58
+ if (num > 1) {
59
+ total * = 2;
60
+ }
61
+ return total;
62
+ }
63
+ ```
64
+
45
65
## Sum of divisors
46
66
47
67
We can use the same argument of the previous section.
48
68
49
69
* If there is only one distinct prime divisor $n = p_1^{e_1}$, then the sum is:
50
-
70
+
51
71
$$1 + p_1 + p_1^2 + \dots + p_1^{e_1} = \frac{p_1^{e_1 + 1} - 1}{p_1 - 1}$$
52
72
53
73
* If there are two distinct prime divisors $n = p_1^{e_1} \cdot p_2^{e_2}$, then we can make the same table as before.
54
74
The only difference is that now we now want to compute the sum instead of counting the elements.
55
75
It is easy to see, that the sum of each combination can be expressed as:
56
-
76
+
57
77
$$\left(1 + p_1 + p_1^2 + \dots + p_1^{e_1}\right) \cdot \left(1 + p_2 + p_2^2 + \dots + p_2^{e_2}\right)$$
58
78
59
79
$$ = \frac{p_1^{e_1 + 1} - 1}{p_1 - 1} \cdot \frac{p_2^{e_2 + 1} - 1}{p_2 - 1}$$
@@ -62,6 +82,33 @@ $$ = \frac{p_1^{e_1 + 1} - 1}{p_1 - 1} \cdot \frac{p_2^{e_2 + 1} - 1}{p_2 - 1}$$
62
82
63
83
$$\sigma(n) = \frac{p_1^{e_1 + 1} - 1}{p_1 - 1} \cdot \frac{p_2^{e_2 + 1} - 1}{p_2 - 1} \cdots \frac{p_k^{e_k + 1} - 1}{p_k - 1}$$
64
84
85
+ ```cpp
86
+ long long SumOfDivisors(long long num) {
87
+ long long total = 1;
88
+
89
+ for (int i = 2; (long long)i * i <= num; i++) {
90
+ if (num % i == 0) {
91
+ int e = 0;
92
+ do {
93
+ e++;
94
+ num /= i;
95
+ } while (num % i == 0);
96
+
97
+ long long sum = 0, pow = 1;
98
+ do {
99
+ sum += pow;
100
+ pow *= i;
101
+ } while (e-- > 0);
102
+ total *= sum;
103
+ }
104
+ }
105
+ if (num > 1) {
106
+ total *= (1 + num);
107
+ }
108
+ return total;
109
+ }
110
+ ```
111
+
65
112
## Multiplicative functions
66
113
67
114
A multiplicative function is a function $f(x)$ which satisfies
0 commit comments