-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14Longest_Collatz_sequence.cpp
More file actions
48 lines (44 loc) · 1.01 KB
/
Copy path14Longest_Collatz_sequence.cpp
File metadata and controls
48 lines (44 loc) · 1.01 KB
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
#include <bits/stdc++.h>
#include<vector>
using namespace std;
int target = 5000001;
vector<long> arr(target, 0);
long countchain(long num)
{
if(arr[num]!=0) return arr[num];
if(num%2==0) arr[num]=1+countchain(num/2);
else {
long temp=0, count=1;
temp=num*3+1;
while(temp>target)
{
if(temp%2==0) temp/=2;
else temp=temp*3+1;
count++;
}
arr[num]=count+countchain(temp);
}
return arr[num];
}
int main()
{
long cas, item;
arr[1]=1;
for(long a=1;a<=target;a++)
{
countchain(a);
}
vector<long> results(target);
results[1] = 1;
for(long a=1;a<=target;a++)
{
if(arr[a] >= arr[results[a-1]]) results[a] = a;
else results[a] = results[a-1];
}
cin >> cas;
for(int c = 0; c < cas; c++) {
cin >> item;
cout << results[item] << endl;
}
return 0;
}