1. 程式人生 > >Project Euler Problem 14

Project Euler Problem 14

Problem 14 : Longest Collatz sequence

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.

#include <iostream>
#include <cassert>

using namespace std;
    
//#define UNIT_TEST

class PE0014
{
public:
    long long int getLongestChain
(long long int maxNumber); long long int genIterativeCollatzSequence(long long int startingNumber); }; long long int PE0014::getLongestChain(long long int maxNumber) { long long int longestChainTerms = 0; long long int longestChainStartingNumber; long long int numOfTerms; for (long
long int number=maxNumber-1; number>=1; number--) { numOfTerms = genIterativeCollatzSequence(number); if (longestChainTerms < numOfTerms) { longestChainTerms = numOfTerms; longestChainStartingNumber = number; } } #ifdef UNIT_TEST cout << "Starting number " << longestChainStartingNumber <<", under " ; cout << maxNumber << ", produces the longest chain containing " ; cout << longestChainTerms << " terms" << endl; #endif return longestChainStartingNumber; } long long int PE0014::genIterativeCollatzSequence(long long int startingNumber) { long long int n = startingNumber; long long int numOfTerms = 1; do { if (n % 2 == 0) // n is even { n /= 2; } else // n is odd { n = 3*n+1; } numOfTerms ++; } while (n > 1); return numOfTerms; } int main() { PE0014 pe0014; assert(10 == pe0014.genIterativeCollatzSequence(13)); cout << "Starting number " << pe0014.getLongestChain(1000000) ; cout << ", under one million, produces the longest chain" << endl; return 0; }