0

I have written this piece of code that finds all Fibonacci numbers that are less than a given number, but when I give a number like 1 million for the given number, my computer just hangs up. is there a way to fix this?

num_limit = int(input('pls enter the number limit: '))
fibbonacci_nums_list = []
x=0
y=x+1

for i in range(1,(num_limit + 1)):
    fibbonacci_nums_list.append(x)
    fibbonacci_nums_list.append(y)
    x=x+y
    y=y+x
for i in range(len(fibbonacci_nums_list)):
    if fibbonacci_nums_list[-1] >= num_limit:
        fibbonacci_nums_list.pop(-1)
print('the fibbonacci nums less than', num_limit, 'are', str(fibbonacci_nums_list))

1 Answers1

3

You are calculating num_limit numbers and then you're removing all numbers larger than num_limit. That means you're calculating 2,000,000 values and removing 1,999,968 of them because there are only 31 fibonacci numbers less than 1,000,000.

You could improve your code by calculating numbers in while loop until they reach num_limit. This could fix your problem:

num_limit = int(input('pls enter the number limit: '))
fibbonacci_nums_list = []
x=0
y=x+1

while x <= num_limit:
    fibbonacci_nums_list.append(x)
    if y <= num_limit:
        fibbonacci_nums_list.append(y)
    x=x+y
    y=y+x

print('the fibbonacci nums less than', num_limit, 'are', str(fibbonacci_nums_list))

I ran your code on wandbox and got an out of memory error for 100,000. The improved version solves it wandbox for 1,000,000.