Euler 0014
The Problem:
ThereWe isare 100 50-digit numbers that neededtrying to befind summedthe together.longest TheCollatz attachedsequence fileunder has been added to do this.1000000.
Considerations:
InThe pythoncollatz thissequence problemfollows 2 simple rules:
- if n is irrelevanteven, becausethen wen/2
- canif fitn giantis numbersodd, intothen then*3 integer+ space1
5 python-> will16 work-> with8 it.-> 4 -> 2 -> 1
6 -> 5 -> 4 -> 3 -> 2 -> 1
The Approach:
WeThe readapproach I'll take to this is to set up a dictionary of lengths at key n. If the file,key sumdoesn't thehave numbers,a convert to string, andvalue then convertit backgenerates intoa numbercollatz aftersequence slicinguntil theit firstreturns 101 digits.or a key that has a length value
The Code:
numbers_filehighest_starting = open("numbers.txt",1000000
"r")
totallengths_dict = 0{1:1}
max_length = 1
length_key = 1
#the recursive function to generate collatz.
#Base case is satisfied by the lengths_dict above already having 1 initialized.
def update_lengths(number, lengths):
#print(number)
if lengths.get(number) == None:
if number % 2 == 0:
one_down = number/2
else:
one_down = number*3 + 1
lengths = update_lengths(one_down, lengths)
lengths[number] = lengths[one_down] + 1
return lengths
for numberi in numbers_file:
totalrange(1,highest_starting + 1):
if lengths_dict.get(i) == int(number)None:
lengths_dict = update_lengths(i, lengths_dict)
if lengths_dict.get(i) > max_length:
length_key = i
max_length = lengths_dict.get(i)
print(str(total)[:10])length_key, max_length)