[447, 283, 463, 29, 23, 487, 463, 993, 119, 883, 327, 493, 423, 159, 743], [217, 623, 3, 399, 853, 407, 103, 983, 89, 463, 290, 516, 212, 462, 350], [960, 376, 682, 962, 300, 780, 486, 502, 912, 800, 250, 346, 172, 812, 350], [870, 456, 192, 162, 593, 473, 915, 45, 989, 873, 823, 965, 425, 329, 803], [973, 965, 905, 919, 133, 673, 665, 235, 509, 613, 673, 815, 165, 992, 326], [322, 148, 972, 962, 286, 255, 941, 541, 265, 323, 925, 281, 601, 95, 973], [445, 721, 11, 525, 473, 65, 511, 164, 138, 672, 18, 428, 154, 448, 848], [414, 456, 310, 312, 798, 104, 566, 520, 302, 248, 694, 976, 430, 392, 198], [184, 829, 373, 181, 631, 101, 969, 613, 840, 740, 778, 458, 284, 760, 390], [821, 461, 843, 513, 17, 901, 711, 993, 293, 157, 274, 94, 192, 156, 574], [ 34, 124, 4, 878, 450, 476, 712, 914, 838, 669, 875, 299, 823, 329, 699], [815, 559, 813, 459, 522, 788, 168, 586, 966, 232, 308, 833, 251, 631, 107], [813, 883, 451, 509, 615, 77, 281, 613, 459, 205, 380, 274, 302, 35, 805]] for r in range(len(A)): for c in range(len(A[0])): A[r][c] *= -1 from munkres import Munkres, print_matrix m = Munkres() indexes = m.compute(A) total = 0 for row, column in indexes: value = A[row][column] total += value #print '(%d, %d) -> %d' % (row, column, value) print -total u.exec_time(p345)
# #Given that F_k is the first Fibonacci number for which the #first nine digits AND the last nine digits are 1-9 #pandigital, find k. from utils import Utils from math import sqrt from decimal import Decimal u = Utils() def is_pandigital(n): return ''.join(sorted(str(n))) == '123456789' def p104(): phi = (1 + sqrt(5)) / 2. c = sqrt(5) i = 2 f = Decimal((phi ** 2) / c) m = str(f)[:10].replace('.', '') a, b = 1, 1 while not (is_pandigital(m) and is_pandigital(a)): a, b = (a + b) % (10 ** 9), a % (10 ** 9) f *= Decimal(phi) m = str(f)[:10].replace('.', '') i += 1 print i u.exec_time(p104)
#which h = b ± 1 and b, L are positive integers. from utils import Utils u = Utils() def p138(): """ Here the problem was reduced to the following Pell equation: (5b ± 4)^2 - 20L^2 = -4, with solutions given by the following recurrences: (a_0, L_0) = (16, 17), (a_{k + 1}, L_{k + 1}) = (9 * a_k + 40 * L_k, 2 * a_k + 9 * L_k), with a_k = 5b_k ± 4 \forall k \geq 0. """ a, L = 76, 17 num_triangles = 1 total = b while num_triangles < 12: a, L = 9 * a + 40 * L, 2 * a + 9 * L if a % 5 == 1 or a % 5 == 4: total += L num_triangles += 1 print total u.exec_time(p138)
#Let p_n be the nth prime: 2, 3, 5, 7, 11, ..., and let r #be the remainder when (p_n − 1)^n + (p_n + 1)^n is divided #by p_n^2. # #For example, when n = 3, p_3 = 5, and 4^3 + 6^3 = 280 #≡ 5 mod 25. # #The least value of n for which the remainder first exceeds #10^9 is 7037. # #Find the least value of n for which the remainder first #exceeds 10^10. from utils import Utils u = Utils() p = u.sieve(4 * (10 ** 5)) def p123(): i = 0 a = 0 while a < 10 ** 10 and i < len(p): i += 1 a = (2 * p[i] * (i + 1)) % (p[i] ** 2) #sum 2 because i is the index of the number just below #10 ** 10, and array indices start by 0: print i + 2 u.exec_time(p123)
#1,000,000,000,000 discs in total, determine the number of #blue discs that the box would contain. from utils import Utils u = Utils() def p100(): """ The number of blue discs, b_k, and the total number of discs in the arrangement, t_k, are solutions to the following Pell equation: x_k^2 - 2y_k^2 = -1, with x_k = 2t_k - 1, y_k = 2b_k - 1, minimal solution given by (x_0, y_0) = (1, 1), and the next solution by the given recurrences: (x_{k + 1}, y_{k + 1}) = (3x_k + 4y_k, 2x_k + 3y_k) for k >= 0. """ x, y = 1, 1 total = (x + 1) / 2 while total < 10 ** 12: x, y = 3 * x + 4 * y, 2 * x + 3 * y total = (x + 1) / 2 print (y + 1) / 2 u.exec_time(p100)
#Using a combination of black square tiles and oblong tiles #chosen from red tiles measuring two units, green tiles #measuring three units, and blue tiles measuring four units, #it is possible to tile a row measuring five units in length #in exactly fifteen different ways. # #How many ways can a row measuring fifty units in length be #tiled? # #NOTE: This is related to Problem 116. from utils import Utils u = Utils() def p117(): l = [0, 1, 2, 4, 8] for i in range(5, 51): l.append(l[-1] + l[-2] + l[-3] + l[-4]) print l[-1] u.exec_time(p117)
# #{20,48,52}, {24,45,51}, {30,40,50} # #For which value of p <= 1000, is the number of solutions #maximised? from utils import Utils def count_solutions(p): total = 0 for a in xrange(1, p): for b in range(a, p): c = p - a - b if 0 < a <= b < c: if c ** 2 == a ** 2 + b ** 2: total += 1 return total def p39(): max_count = -1 perimeter = -1 for p in range(4, 1001, 2): m = count_solutions(p) if m > max_count: max_count = m perimeter = p print max_count, perimeter u = Utils() u.exec_time(p39)
c = str_num[-1] str_num = str_num[:-1] c += str_num str_num = c lista.append(c) i += 1 return map(int, lista) def all_in(l1, l2, u): for n in l1: if u.chop(n, l2) == -1: return False return True def p35(): u = Utils() sieve = u.sieve(10 ** 6) count = 0 for prime in sieve: s = str(prime) l = cyclic_shifts_of(s) if all_in(l, sieve, u): count += 1 return count def exec_(): print p35() u = Utils() u.exec_time(exec_)
# #If we list the set of reduced proper fractions for d <= 8 #in ascending order of size, we get: # #1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, #3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8. # #It can be seen that 2/5 is the fraction immediately to the #left of 3/7. # #By listing the set of reduced proper fractions for #d <= 1,000,000 in ascending order of size, find the #numerator of the fraction immediately to the left of 3/7. from fractions import gcd from utils import Utils #This just does a brute-force search; fortunately enough, #it finds the correct solution within a proper time limit. #This one needs to be revised to remember how did I do it. def p71(): min_a, min_b = 2, 5 for k in xrange(10 ** 6): b, a = 5 + 7 * k, 2 + 3 * k if min_a * b < min_b * a and 7 * a < 3 * b and b < 10 ** 6: min_a, min_b = a, b print(min_a, min_b, gcd(min_a, min_b)) u = Utils() u.exec_time(p71)
def is_right_truncatable(p, u, sieve): while p > 10: p /= 10 if u.chop(p, sieve) == -1: return False return True def is_left_truncatable(p, u, sieve): p_str = str(p) while len(p_str) > 1: p_str = p_str[1:] if u.chop(int(p_str), sieve) == -1: return False return True def p37(): u = Utils() primes = u.sieve(10 ** 6) total = 0 for p in primes: a = is_right_truncatable(p, u, primes) b = is_left_truncatable(p, u, primes) if a and b: total += p #we have to ignore 2, 3, 5, and 7, which sum up to 17: print total - 17 u = Utils() u.exec_time(p37)
# insert, so check that first. # Else, if the item is in the list then it has to be at # index bisect_left(lst, item). return (item <= lst[-1]) and \ (lst[bisect_left(lst, item)] == item) import time def p50(): #initial values: k = 2 p1 = u.sieve(10 ** 6) pl = k_consecutive_prime_sums(p1, k, 10 ** 6) m = len(pl) max_k = -1 p_k = 0 #creating the k-prime sums given the (k - 1)-prime sums: while m > 0: m = len(pl) - 1 pl = [pl[i] + p1[i + k] for i in range(m) if pl[i] + p1[i + k] < 10 ** 6] k += 1 for prime in pl: if bi_contains(p1, prime) and k > max_k: max_k = k p_k = prime print max_k, p_k u.exec_time(p50)
continue while n_ % p == 0: n_ /= p if n_ < len(l): l.append(p * l[int(n_)]) break i += 1 return l def p127(max_c, exp): u = Utils() primes = u.sieve(max_c) radicals = rad(int(max_c), primes) possible_ys = [i for i in range(1, max_c) if radicals[i] <= int(max_c ** exp)] possible_rads = [radicals[i] for i in possible_ys] print("len(radicals):", len(radicals)) print("len(possible_ys):", len(possible_ys)) print(possible_ys) print(possible_rads) total = 0 for a in possible_ys: for b in possible_ys: c = a + b if a < b and c < max_c and hit(a, b, c, radicals): print(a,b,c) total += c print(total) u = Utils() u.exec_time(lambda: p127(120000, 0.8))
#Surprisingly, there are palindromic numbers that are #themselves Lychrel numbers; the first example is 4994. # #How many Lychrel numbers are there below ten-thousand? # #NOTE: Wording was modified slightly on 24 April 2007 to #emphasise the theoretical nature of Lychrel numbers. from utils import Utils u = Utils() def is_lychrel(n): iterations = 0 while iterations < 50: n += int(str(n)[::-1]) iterations += 1 if u.is_palindrome(str(n)): return False return True def p55(): total = 0 for n in range(1, 10000): if is_lychrel(n): total += 1 print total u.exec_time(p55)
squares = [i * i for i in range(1, 101)] #start searching at 15: o = 15 while o < 5800: #is the test number prime? if u.chop(o, primes) != -1: #yeap, go to next one: o += 2 continue #nope, begin testing: ind = 0 found = False while o - primes[ind] > 0: s = (o - primes[ind]) / 2 #found desired decomposition? if u.chop(s, squares) != -1: #yep, break out: found = True break #nope, try next prime: else: ind += 1 #found possible candidate: if not found: print o #keep searching: o += 2 u = Utils() u.exec_time(p46)
#angle between these lines: theta0 = atan((mr[1] - mt[1]) / (1 + (mr[1] * mt[1]))) #print 'theta = {0} rad'.format(theta0) #get reflected ray equation: mr_, br_ = u.rotate_line(mt, bt, pt, -theta0) #print mr_, br_ #Solve equation given its coefficients. This solves #for the parameter t!!! a = (4 * mr_[0] * mr_[0]) + (mr_[1] * mr_[1]) b = (8 * mr_[0] * br_[0]) + (2 * mr_[1] * br_[1]) c = (4 * br_[0] * br_[0]) + (br_[1] * br_[1]) - 100 t = u.solve_quadratic(a, b, c) #get right coordinate: ps = [u.get_point(mr_, br_, t[0]), u.get_point(mr_, br_, t[1])] return ps[1 if close_enough(ps[0], pt) else 0] def p144(): i = 0 p, pt = [0.0, 10.1], [1.4, -9.6] while (-0.01 > pt[0] or pt[0] > 0.01) or pt[1] < 0: p, pt = pt, next_point(p, pt) i += 1 print i u.exec_time(p144)
#Find the least value of n for which p(n) is divisible by #one million. from utils import Utils u = Utils() p = [1, 1] def part2(n): sum, k, a, b, sgn = 0, 4, 2, 1, 1 while n >= a: sum += sgn * (p[n - a] + p[n - b]) a += k + 1 b += k sgn *= -1 k += 3 if n >= b: sum += sgn * p[n - b] return sum % (10 ** 6) def p78(): i = 1 while p[i] != 0: i += 1 d = part2(i) p.append(d) print i u.exec_time(p78)
#There are exactly ten ways of selecting three from five, #12345: # #123, 124, 125, 134, 135, 145, 234, 235, 245, and 345. # #In combinatorics, we use the notation, 5C3 = 10. # #In general, # #nCr= n!/(r!(n−r)!), where r <= n, n! = #n x (n−1) x ... x 3 x 2 x 1, and 0! = 1. It is not until #n = 23, that a value exceeds one-million: 23C10 = 1144066. # #How many, not necessarily distinct, values of nCr, for #1 <= n <= 100, are greater than one-million? from utils import Utils def p53(): u = Utils() mat, val = u.binom(100, 100) total = 0 for r in range(len(mat)): for c in range(len(mat[0])): if mat[r][c] > 10 ** 6: total += 1 print total u = Utils() u.exec_time(p53)
#Pentagonal Pn = n(3n - 1)/2: 1, 5, 12, 22, 35, ... #Hexagonal Hn = n(2n - 1): 1, 6, 15, 28, 45, ... # #It can be verified that T_285 = P_165 = H_143 = 40755. # #Find the next triangle number that is also pentagonal and #hexagonal. from utils import Utils def p45(): u = Utils() a, b = 1, 1 i = 0 h_, k_, r_ = 0, 0, 0 while i < 3: a, b = 2 * a + 3 * b, a + 2 * b if a % 6 == 5 and b % 2 == 1: #triangular: h_ = (b - 1) / 2 #pentagonal: k_ = (a + 1) / 6 if h_ % 2 == 1: #hexagonal: r_ = (h_ + 1) / 2 i += 1 print u.t(h_) u = Utils() u.exec_time(p45)
#this property the value of n is unique, and there are only #four such primes below one-hundred. # #How many primes below one million have this remarkable #property? from utils import Utils cube_list = [x ** 3 for x in range(578)] u = Utils() prime_list = u.sieve(10 ** 6) def p131(): """ As taken from the forum: Since x^3 = n^2(n + p), and p is a prime, it turns out that n must be a cube, as well as n + p, i.e., we must have p = a^3 - b^3 for some a, b. But, for a^3 - b^3 = (a - b)(a^2 + ab + b^2) to be prime we must have a - b = 1, so p must be a difference of consecutive cubes. """ total = 0 for i in range(len(cube_list) - 1): p_ = cube_list[i + 1] - cube_list[i] total += (u.chop(p_, prime_list) != -1) print total u.exec_time(p131)
#A googol (10^100) is a massive number: one followed by #one-hundred zeros; 100^100 is almost unimaginably large: #one followed by two-hundred zeros. Despite their size, the #sum of the digits in each number is only 1. # #Considering natural numbers of the form, a^b, where #a, b < 100, what is the maximum digital sum? from utils import Utils def digit_sum(a, b): m = a ** b s = str(m) total = reduce(lambda x, y: x + y, map(int, s)) return total def p56(): max = -1 max_a, max_b = 0, 0 for a in range(100): for b in range(100): m = digit_sum(a, b) if m > max: max = m max_a = a max_b = b print m, max_a, max_b u = Utils() u.exec_time(p56)
# #X(-175,41), Y(-421,-714), Z(574,-645) # #It can be verified that triangle ABC contains the origin, #whereas triangle XYZ does not. # #Using triangles.txt (right click and 'Save Link/Target #As...'), a 27K text file containing the co-ordinates of one #thousand "random" triangles, find the number of triangles #for which the interior contains the origin. # #NOTE: The first two examples in the file represent the #triangles in the example given above. from utils import Utils u = Utils() def p102(): total = 0 P = [0, 0] triangles = [] for line in open('../data/p102_triangles.txt'): a1, a2, b1, b2, c1, c2 = map(int, line.split(',')) total += u.in_triangle(P, [(a1, a2), (b1, b2), (c1, c2)]) print total u.exec_time(p102)
#The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. # #Find the last ten digits of the series, 1^1 + 2^2 + 3^3 # + ... + 1000^1000. from utils import Utils def p48(): print(sum([k ** k for k in range(1, 1001)]) % (10 ** 10)) u = Utils() u.exec_time(p48)
m, val = u_.binom(11, 11) def u(n): return n ** 10 - n ** 9 + n ** 8 - n ** 7 + n ** 6 - n ** 5 + n ** 4 - n ** 3 + n ** 2 - n + 1 U = [u(j) for j in range(1, 12)] def fit(n): l = [((-1) ** (p + (n % 2))) * m[n][p - 1] * U[p - 1] for p in range(1, n + 1)] return sum(l) def p101(): """ Turns out that after some algebraic manipulation with the formula for the interpolation polynomial (http://en.wikipedia.org/wiki/Polynomial_interpolation), we found the following formula for BOP(k): BOP(k) = \sum_1^l{(-1)^{l + r}{k \choose {l - 1}}u_l}, where n \equiv r \pmod 2, so, it was just a matter of implementing the sum: """ print sum([fit(l) for l in range(1, len(U))]) u_.exec_time(p101)
#As...'), a 22K text file containing one thousand lines with #a base/exponent pair on each line, determine which line #number has the greatest numerical value. # #NOTE: The first two lines in the file represent the numbers #in the example given above. from utils import Utils u = Utils() def p99(): base_exp = open("../data/p99_base_exp.txt", "r") number_list = base_exp.readlines() max_val = -1 ind = 1 max_ind = -1 from math import log10 for line in number_list: s = line.split(',') a, b = float(s[0]), float(s[1]) d = b * log10(a) if d > max_val: max_ind = ind max_val = d ind += 1 print max_ind u.exec_time(p99)
while j < max: x, y = a * x + D * b * y, b * x + a * y j+= 1 l.append(y) return l def p140(): #so, the idea here is to find at least 28 solutions #with x % 5 = 2 (which luckily are among the first 90, #the first 15 from each solution set), and sum them up: ys = sol_set([7, 1], [9, 4], 5) + \ sol_set([8, 2], [9, 4], 5) + \ sol_set([13, 5], [9, 4], 5) + \ sol_set([17, 7], [9, 4], 5) + \ sol_set([32, 14], [9, 4], 5) + \ sol_set([43, 19], [9, 4], 5) xs = map(lambda y: int(sqrt(5 * (y ** 2) + 44)), ys) xs_ = [(k - 7) / 5 for k in xs if k % 5 == 2] final = sorted(xs_) #here, n = 2 is generated by (17, 7), and n = 5 by #(32, 14), both fundamental independent solutions to #x^2 - 5y^2 = 44, so they are not returned by #sol_set(), hence we have to sum them up in the end: print sum(final[:28]) + 7 u.exec_time(p140)
MAX = 200000 def get_exp(n, p): i = 0 while n % p == 0: i += 1 n = n / p return i prime_list = u.sieve(MAX) #calculating the desired number using memoization, stopping #as soon as we find it: def p108(): i = 2 l = [0, 1] while i < MAX: for p in prime_list: if i % p == 0: val = l[i / p] + \ 2 * l[i / (p ** get_exp(i, p))] - 1 if val >= 1000: print i return else: l.append(val) break i += 1 u.exec_time(p108)
return a or b def p19(): total = 0 start = 1 # jan 1st, 1900 is monday: common = [3, 0, 3, 2, 3, 2, 3, 3, 2, 3, 2] leap = [3, 1, 3, 2, 3, 2, 3, 3, 2, 3, 2] for year in range(1901, 2001): # get first day of the year, 0 is sunday: a = 2 if is_leap(year - 1) else 1 y = leap if is_leap(year) else common start = (start + a) % 7 tmp = start # get first days of year's months: f = [] for d in y: tmp += d tmp %= 7 f.append(tmp) # count sundays: g = [x for x in f if x == 0] # add the count to the total, adding the first day # if it was sunday: t = len(g) if start != 0 else len(g) + 1 total += t print total u.exec_time(p19)
#coding: UTF-8 #Let r be the remainder when (a−1)^n + (a+1)^n is divided #by a^2. # #For example, if a = 7 and n = 3, then r = 42: 6^3 + 8^3 = #728 ≡ 42 mod 49. And as n varies, so too will r, but for #a = 7 it turns out that rmax = 42. # #For 3 ≤ a ≤ 1000, find ∑ rmax. from utils import Utils u = Utils() def p120(): total = 0 for a in range(3, 1001): max_n = (a - 1) / 2 if (a % 2 == 1) else (a - 2) / 2 total += 2 * a * max_n print total u.exec_time(p120)
#are: # #2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, #1457/536, ... The sum of digits in the numerator of the 10th #convergent is 1+4+5+7=17. # #Find the sum of digits in the numerator of the 100th #convergent of the continued fraction for e. from utils import Utils u = Utils() def p65(): a = [1, 1] b =[2] for k in range(1, 34): b += [1, 2 * k, 1] A = [2, 3] B = [1, 1] for j in range(2, 100): A.append(b[j] * A[-1] + A[-2]) B.append(b[j] * B[-1] + B[-2]) print u.power_sum(A[-1], 1) u.exec_time(p65)
Now, since x has to be rational, it follows that 5n^2 + 2n + 1 = y^2 for some integer y, which leads us to the following Pell equation: (5n + 1)^2 - 5y^2 = -4. It is known (and somehow easy enough to prove) that this equation has infinitely many integer solutions (x_k, y_k), and that y_k = F_{2k + 1} \forall k \geq 0, the Fibonacci numbers of odd index. So we just have to find which of the odd indexed Fibonacci numbers generates an x congruent to 1 modulo 5 to get n out of it: """ a, b, i, j, n = 1, 1, 2, 0, 0 while j < 15: a, b = a + b, a i += 1 if i % 2 == 1: x = int(sqrt(5 * (a ** 2) - 4)) if x % 5 == 1: j += 1 if j == 15: n = (x - 1) / 5 print n u.exec_time(p137)