0

I was trying to output F(n) mod m to find the remainder of Fibonacci number, where F(n) could be a very big number:

# Uses python3
n, m =  [int(x) for x in input().split()]

def fib(n):
    a = [0, 1]
    if (n <=1):
        return n
    else:
        for i in range(1, n):
            a.append((a[-1] + a[-2])%m)
        return a[i+1]
print (fib(n))

As I typed in 239 1000, it returns 161 as the remainder, which is correct. But with bigger inputs eg. 2816213588 239, it seems to exceed time limits, what can I do to improve the code? Thanks.

djriles
  • 63
  • 1
  • 4
  • 1
    Maybe you don't need to store every number in a list. You only need the preceding two numbers so you can calculate the next. – khelwood May 18 '19 at 07:36
  • Your question should be asked here - https://codereview.stackexchange.com/ – Justin May 18 '19 at 11:03

0 Answers0