f(n) ={n/2. if n is even ,3n+1.if n is odd
Answers
Step-by-step explanation:
f 0 vote
My answer in C++
I got 261 as a result...not sure if it's correct
#include <iostream>
#include <unordered_map>
using namespace std;
unordered_map<int, int> col;
unordered_map<int, int> path_length;
int F(int n)
{
if (col.count(n) != 0)
return col[n];
if (n % 2 == 0)
col.insert({ n, n / 2 });
else
col.insert({ n, (3 * n + 1) });
return col[n];
}
int FindPathLength(int num )
{
if (path_length.count(num) != 0)
return path_length[num];
int f = F(num);
if (f == 1)
{
path_length.insert({ num, 0 });
return 1;
}
int r = FindPathLength(f);
path_length.insert({ f, r });
return (1 + r);
}
int GetLongestCollapseSequence(int n)
{
int max = INT_MIN;
for (int i = 1; i < n; ++i)
{
//cout << i << endl;
int curr = FindPathLength(i);
if (curr > max)
{
max = curr;
//cout << "max is now " << max << " for i " << i << endl;
}
}
return max;
}
void main_collapse_seq(void)
{
cout << GetLongestCollapseSequence(10000)<< endl;
}
- A July 05, 2017 | Flag