Created
July 7, 2021 01:24
-
-
Save FernandoLins8/a9897d0206acdcbd280c32f05f2ea3f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import perf_counter | |
t1_start = perf_counter() | |
biggest_sequence_len = 0 | |
biggest_sequence_value = 0 | |
sequences_len_sum = 0 | |
def ulam_algorithm(initial_value): | |
global biggest_sequence_len | |
global biggest_sequence_value | |
global sequences_len_sum | |
x = initial_value | |
seq = [x] | |
while len(seq) < 3 or (seq[-3] != 4 and | |
seq[-2] != 2 and seq[-1] != 1): | |
if(x % 2 == 0): | |
x = x/2 | |
else: | |
x = 3 * x + 1 | |
seq.append(x) | |
if len(seq) > biggest_sequence_len: | |
biggest_sequence_len = len(seq) | |
biggest_sequence_value = initial_value | |
sequences_len_sum += len(seq) | |
return seq | |
with open('answer.txt', 'w') as file: | |
for i in range(1, 65535 + 1): | |
file.writelines(str(i) + ': [' + ', '.join(str(int(number)) for number in ulam_algorithm(i)) + ']\n\n') | |
t1_stop = perf_counter() | |
print(f'The biggest sequence length was {biggest_sequence_len} for the value {biggest_sequence_value}') | |
print(f'The average sequence length was {sequences_len_sum/65535}') | |
print(f'Time in seconds to run: {t1_stop-t1_start}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment