import sys s = sys.stdin.readline().split(" ") n = int(s[0]) m = int(s[1]) a = 0 b = 1 f = 1 mem = [a, b] for c in range(2, n+1): f = (a + b) % m a = b b = f if a == 0 and f == 1: mem.pop() break else: mem.append(f) pos = n % len(mem) print(mem[pos])
Online example here: ideone.com/6pl4AR