Project Euler Homework
Classes | Functions

014.cpp File Reference

Find the longest sequence using a starting number under one million. More...

#include <iostream>

Go to the source code of this file.

Classes

class  sequence
class  table_list

Functions

int main ()

Detailed Description

Find the longest sequence using a starting number under one million.

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.

Definition in file 014.cpp.


Function Documentation

int main ( )

Why only search numbers in range [500001,1e6)?

Because for all x in [1,500000] there exist an integer 2x in [500001,1e6). So the sequence starting with 2x is longer than that of x. e.g. 500002 -> 250001 -> ...

Replace x % 2 with x&1 which is more efficient.

A look up table is established to store any integer evaluated which is between k and 1e6. This reduce duplicated case. e.g. 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 Then 4,5,8,10,16 are not needed.

Definition at line 73 of file 014.cpp.

 All Classes Files Functions Variables