def crt(a): '''Returns the basic solution to the system x = a[i][0] (mod a[i][1]), i=0..len(a)-1 using the Chinese Remainder Theorem. All a[i][1] must be co-prime (although a weaker condition involving the a[i][0]''s is also sufficient for a solution, this implementation is not guaranteed to work for it).''' a, n = zip(*a) N = np.prod(map(long, n)) return sum(a[i] * (N / n[i]) * inv_mod(N / n[i], n[i]) for i in xrange(len(a))) % N
def Fnx(n, m, x): '''Yields Fn(x) mod m for x,m s.t. gcd(1-x-x^2,m)=1.''' F = Fib(r=m) xn = pow(x, n, m) return (inv_mod(1 - x - x * x, m) * ((x * (1 - F(n + 1) * xn - F(n) * xn * x)) % m)) % m