Project Euler #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.

I solved this problem in both Python, and C++.

C++

#include <iostream>

// Returns calculated collatz chain length
unsigned long long collatzCalc(unsigned long long currentNumber); 

int main(void)
{
	// Create variables to hold compared chain lengths
	unsigned long long chainBuff = 0;
	unsigned long long longestChain = 0;
	int longestSeed;
	// Iterate through all numbers under one million
	for(unsigned long long currentNumber = 1; currentNumber < 1000000; currentNumber++) { // Pass the calculated chain length to the buffer variable chainBuff = collatzCalc(currentNumber); // Compares the buffered chain length against the current longest chain if(chainBuff > longestChain)
		{
			// Replaces if greater
			longestChain = chainBuff;
			longestSeed = currentNumber;
		}
	}

	std::cout << longestSeed << " is the seed of the longest chain, " << longestChain << ", under one million";
}


unsigned long long collatzCalc(unsigned long long currentNumber)
{
	unsigned long long collatzLength = 1;

	while(currentNumber != 1)
	{
		if(currentNumber & 0x1) // if it is odd
		{
			currentNumber += (2*currentNumber) + 1; // Set it equal to 3n + 1 
		}
		else // it is even
		{
			currentNumber /= 2; // Set it equal to n/2
		}
		collatzLength++;
	}
	return ++collatzLength; 
}

Python

longestChain = 0
longestNumb = 0

for i in range(1,1000000):
	currentChain = 1
	currentNumber = i
	
	while(currentNumber != 1):
		
		if(currentNumber & 0x1):
			currentNumber += ((2*currentNumber) + 1)

		else:
			currentNumber /= 2
		
		currentChain += 1
	
	if(++currentChain > longestChain):
		longestChain = currentChain
		longestNumb = i	

print "The longest Collatz sequence under one million is %d" % (longestChain)
print "Which starts with %d as the seed" % (longestNumb)

Leave a Reply

Your email address will not be published. Required fields are marked *