Commit 2c1d4756 by Andrew Dahl

Solved Problem 14

parent d9387e37
Showing with 52 additions and 0 deletions
Question:
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
Answer: 837799
#include <iostream>
#include <vector>
using namespace std;
#define even(x) x/2
#define odd(x) x*3+1
int main() {
int longest = 0;
int max = 1000000;
int biggest = 0;
long int num = 0;
vector<int> numbers;
for(int i = 1; i <= max; i++)
{
num = i;
while(num != 1)
{
numbers.push_back(num);
num = (num % 2 == 0) ? even(num) : odd(num);
}
if(numbers.size() > longest)
{
longest = numbers.size();
biggest = i;
}
numbers.clear();
}
cout << biggest << endl;
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment