-
Notifications
You must be signed in to change notification settings - Fork 24
/
breaking-sticks.cpp
67 lines (51 loc) · 1.07 KB
/
breaking-sticks.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
// Mathematics > Number Theory > Breaking Sticks
// Find the length of the longest sequence of moves.
//
// https://www.hackerrank.com/challenges/breaking-sticks/problem
// https://www.hackerrank.com/contests/world-codesprint-12/challenges/breaking-sticks
// challenge id: 30186
//
#include <bits/stdc++.h>
using namespace std;
long single_bar(long n)
{
long moves = 1;
// décomposition en facteurs premiers
// et calcul du nombre de "mouvements" au fur et à mesure
long i = 2;
while (i * i <= n)
{
while (n % i == 0)
{
n /= i;
moves = moves * i + 1;
}
i += (i >= 3) ? 2 : 1;
}
if (n > 1)
moves = moves * n + 1;
return moves;
}
long longestSequence(const vector<long>& a)
{
long moves = 0;
for (auto n : a)
{
moves += single_bar(n);
}
return moves;
}
int main()
{
vector<long> a;
int n;
cin >> n;
while (n--)
{
long x;
cin >> x;
a.push_back(x);
}
cout << longestSequence(a) << endl;
return 0;
}