CodeWords

Code, in words.

Project Euler Problem #14 Solution

leave a comment »

We calculate the length of each Collatz sequence with starting number n \in [1, 10^6) \cap \mathbb{N} and find the value of n for which the length is maximum.

Note that we actually calculate one less than the length of each sequence, but since that subtraction is applied to each length, it doesn’t matter.

def is_even(n):
	return n % 2 == 0

def collatz_length(n):
	length = 0
	while n > 1:
		length += 1
		if is_even(n):
			n /= 2
		else:
			n = 3 * n + 1
	return length

max_n = 0
max_len = 0
for n in range(1, 1000000):
	len = collatz_length(n)
	if len > max_len:
		max_len = len
		max_n = n

print max_n

Advertisement

Written by Jeff

11 February 2011 at 10:21 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.