-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_numbers_with_same_amount_of_divisors.cpp
61 lines (42 loc) · 1.72 KB
/
find_numbers_with_same_amount_of_divisors.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
//The integers 14 and 15, are contiguous (1 the difference between them, obvious) and have the same number of divisors.
//14 ----> 1, 2, 7, 14 (4 divisors)
//15 ----> 1, 3, 5, 15 (4 divisors)
//The next pair of contiguous integers with this property is 21 and 22.
//21 -----> 1, 3, 7, 21 (4 divisors)
//22 -----> 1, 2, 11, 22 (4 divisors)
//We have 8 pairs of integers below 50 having this property, they are:
//[[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]]
//Let's see now the integers that have a difference of 3 between them. There are seven pairs below 100:
//[[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]]
//Let's name, diff, the difference between two integers, next and prev, (diff = next - prev) and nMax, an upper bound of the range.
//We need a special function, count_pairsInt(), that receives two arguments, diff and nMax and outputs the amount of pairs of integers that fulfill this property, all of them being smaller (not smaller or equal) than nMax.
//Let's see it more clearly with examples.
//count_pairsInt(1, 50) -----> 8 (See case above)
//count_pairsInt(3, 100) -----> 7 (See case above)
//Happy coding!!!
#include <cmath>
unsigned int getDivisors(const unsigned int num)
{
int result = 0;
for (int i = 1, root = std::sqrt(num); i <= root; ++i)
{
if (!(num % i)) {
if ((num / i) == i) {
result++;
} else {
result += 2;
}
}
}
return result;
}
unsigned int countDivisors(const unsigned int diff, const unsigned int nMax)
{
int divisors = 0;
for (int prev = 0, next = prev + diff; next < nMax; ++prev, ++next)
{
if (getDivisors(prev) == getDivisors(next))
divisors++;
}
return divisors;
}