Skip to content

Instantly share code, notes, and snippets.

@logalleon
Created July 14, 2015 02:48
Show Gist options
  • Save logalleon/dc0346bcf15201e1625d to your computer and use it in GitHub Desktop.
Save logalleon/dc0346bcf15201e1625d to your computer and use it in GitHub Desktop.
Project Euler 14
#include <iostream>
#include <algorithm>
using namespace::std;
int chainLength(unsigned long long x){
int len = 1;
while (x > 1){
if (x % 2) x = 3*x + 1;
else x /= 2;
len++;
}
return len;
}
// Max to count to.
int longestChain(unsigned long long x){
int length = 0;
int temp;
int index =0 ;
for (unsigned long long i = x; i > 0; i-- ){
temp = chainLength(i);
if (temp > length){
length = temp;
index = i;
}
}
return index;
}
void printCollatz(int x){
cout << x;
while (x > 1){
if (x % 2){
x = 3*x + 1;
cout << " --> " << x;
}
else {
x /= 2;
cout << " --> " << x;
}
}
}
int main(void){
int index = 0;
unsigned long long x = 1000000;
int longest = longestChain(x);
cout << longest << " has the longest chain for numbers less than " << x;
cout << "\nThat chain is " << chainLength(longest) << " long.";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment