-1

This code gives out a fibonacci number. With larger number it produces memory error. Can i allocate more ram or resources to the compiler or is there a more efficient code that i can use?

list1 = [0, 1]
x = 0
while x < 1000000:
    list1.append(list1[-1] + list1[-2])
    x+=1
print(list1[-1])
Joe
  • 6,758
  • 2
  • 26
  • 47
soap
  • 1
  • 2

2 Answers2

4

If you are interested in the last number, don't store the intermediate results.

I just tried it (using sys.getsizeof()) and the sum of all integer values in the list would be 46308778320 bytes. Which is 46 GByte.

Even though the 1000000th Fibobacci number only has 92592 bytes

There is no limit to how big an integer can be in Python.

This is how the size of the integers grows:

enter image description here

A small integer in Python has already has 28 bytes, which is quite large compared to a C int.

More info on this can be found at "sys.getsizeof(int)" returns an unreasonably large value?

How to calculate the total size?

import sys
fib = None
size_fib = 0

for _ in range(1000000):
    fib = ... # calculation here
    size_fib += sys.getsizeof(fib)

print(size_fib)
Joe
  • 6,758
  • 2
  • 26
  • 47
0

I found the 1000000th Fibobacci number using the following code, it took a minute or so to calculate the result.

cache = {}
for x in range(1, 1000001):
    if x > 4:
        cache.pop(x-3, x-4)

    if x <= 2:
        value = 1
        cache[x] = value
    else:
        value = cache[x - 1] + cache[x - 2]
        cache[x] = value
print(value)
soap
  • 1
  • 2