def I(n): terms = [] for (p,k) in factor(n): if p % 2 == 0 and k>1: residues = (1, -1, (1<<k-1)-1, (1<<k-1)+1) else: residues = (1, -1) pk = p**k coef = n // pk * modInverse(n // pk, pk) terms.append(map(lambda x: x*coef, residues)) return max(filter(lambda x: x != n-1, (sum(res) % n for res in cross(*terms))))
def solve(): piter = allprimes() next(piter) next(piter) p1 = next(piter) p2 = next(piter) nextMag = 10 accum = 0 while p1 <= 1000000: while nextMag < p1: nextMag *= 10 accum += p1 + nextMag * ((p2 - p1) * modInverse(nextMag, p2) % p2) (p1, p2) = (p2, next(piter)) return accum
def solve(): reverseOps = { "D": Polynomial(0, 3), "U": Polynomial(Fraction(-1, 2), Fraction(3, 4)), "d": Polynomial(Fraction(1, 2), Fraction(3, 2)), } seq = "UDDDUdddDDUDDddDdDddDDUDDdUUDd" poly = reduce(lambda accum, op: reverseOps[op](accum), seq[::-1], Polynomial.X) # The resulting polynomial is of the form $(a/b)x + c/b$. (Note that the # denominators are equal.) We then need to find the smallest $z > 10^{15}$ # that is in the range of this polynomial, i.e., the smallest $z > 10^{15}$ # such that its preimage $(z - c/b)(b/a) = (zb - c)/a$ is an integer, i.e., # such that $a$ divides $zb - c$, i.e., such that $z$ is congruent to # $cb^{-1}$ _modulo_ $a$. a = poly.coef(1).numerator b = poly.coef(1).denominator c = poly.coef(0).numerator rem = (c * modInverse(b, a)) % a return (10 ** 15 // a + (10 ** 15 % a > rem)) * a + rem
def S(p): inv2 = modInverse(-2, p) inv3 = modInverse(-3, p) inv4 = modInverse(-4, p) return (inv2 * (1 + inv3 * (1 + inv4))) % p