14 Longest Collatz Sequence
#include <iostream>
#include <limits>
#include <vector>
#include <utility>
using namespace std;
void pause() { cin.ignore(numeric_limits<streamsize>::max(), '\n'); }
bool isEven(long long int n)
{
if (n % 2 == 0) return true;
else return false;
}
long long int ifEven(long long int n)
{
return n / 2;
}
long long int ifOdd(long long int n)
{
return (3 * n + 1);
}
long long int findMaxChain(vector <pair <long long int, long long int>> chain)
{
long long int max1 = chain.at(0).first;
long long int max2 = chain.at(0).second;
for (long long int i = 1; i < chain.size(); i++)
{
if (chain.at(i).first > max1)
{
max1 = chain.at(i).first;
max2 = chain.at(i).second;
}
}
return max2 - 1;
}
int main()
{
long long int sequence = 1;
long long int endingNumber = 1000000;
long long int counterChain = 1;
long long int helper = 0;
pair <long long int, long long int> counterChain_sequence;
vector <pair <long long int, long long int>> counters; // format: (1 - 999999) by index - to - counterChains
for (long long int i = 0; i < endingNumber; i++)
{
while (true)
{
if (sequence == 1)
{
helper++;
sequence = sequence + helper;
counterChain_sequence = make_pair(counterChain, sequence);
counters.push_back(counterChain_sequence);
counterChain = 1;
break;
}
if (isEven(sequence))
{
sequence = ifEven(sequence);
counterChain++;
}
else
{
sequence = ifOdd(sequence);
counterChain++;
}
}
}
cout << "Max Number Chain = " << findMaxChain(counters);
pause();
}Last updated