F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the first term in the Fibonacci sequence to contain 1000 digits? NOTE(durandal): the auto-grader seems to want the *index* of the first such term; in the baby example, the correct answer would be 12, not 144. ''' import common def euler025(digits): for i,f in enumerate(common.fibs()): if len(str(f)) >= digits: return i common.assertEquals(12, euler025(3)) common.submit(euler025(1000), expected=4782)
''' 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? ''' import common def euler016(n): return sum(int(d) for d in str(2**n)) common.assertEquals(26, euler016(15)) common.submit(euler016(1000), expected=1366)
1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? ''' import common import itertools def pandigital(s): return sorted(s) == ['1', '2', '3', '4', '5', '6', '7', '8', '9'][:len(s)] common.assertEquals(True, pandigital('1')) common.assertEquals(False, pandigital('5')) common.assertEquals(True, pandigital('123456789')) common.assertEquals(True, pandigital('987654321')) common.assertEquals(False, pandigital('112233445')) def concatenated_product(n): string = '' for i in itertools.count(1): string += str(n * i) if len(string) >= 9: break if i > 1 and pandigital(string): # print n, range(1, i+1), string return int(string) else:
''' 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? ''' import common def euler005(limit): return reduce(common.lcm, range(1, limit + 1)) common.assertEquals(2520, euler005(10)) common.submit(euler005(20), expected=232792560)
[21,36,23, 9,75, 0,76,44,20,45,35,14, 0,61,33,97,34,31,33,95], [78,17,53,28,22,75,31,67,15,94, 3,80, 4,62,16,14, 9,53,56,92], [16,39, 5,42,96,35,31,47,55,58,88,24, 0,17,54,24,36,29,85,57], [86,56, 0,48,35,71,89, 7, 5,44,44,37,44,60,21,58,51,54,17,58], [19,80,81,68, 5,94,47,69,28,73,92,13,86,52,17,77, 4,89,55,40], [ 4,52, 8,83,97,35,99,16, 7,97,57,32,16,26,26,79,33,27,98,66], [88,36,68,87,57,62,20,72, 3,46,33,67,46,55,12,32,63,93,53,69], [ 4,42,16,73,38,25,39,11,24,94,72,18, 8,46,29,32,40,62,76,36], [20,69,36,41,72,30,23,88,34,62,99,69,82,67,59,85,74, 4,36,16], [20,73,35,29,78,31,90, 1,74,31,49,71,48,86,81,16,23,57, 5,54], [ 1,70,54,71,83,51,54,69,16,92,33,48,61,43,52, 1,89,19,67,48]] def line_product(data, startx, starty, dx, dy, length=4): try: product = 1 for k in range(length): product *= DATA[startx + dx*k][starty + dy*k] return product except IndexError: return 0 common.assertEquals(1788696, line_product(DATA, 6, 8, 1, 1)) result = max(line_product(DATA, i, j, di, dj) for i in range(len(DATA)) for j in range(len(DATA[i])) for di,dj in [(1,1), (1,0), (0,1), (1,-1)]) common.submit(result, expected=70600674)
It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000 ''' import common import itertools def sequence(): for i in itertools.count(1): for d in str(i): yield int(d) def euler040(indices): return common.product( d for i, d in enumerate(itertools.islice(sequence(), max(indices))) if i + 1 in indices) common.assertEquals(1, euler040([12])) result = euler040([1, 10, 100, 1000, 10000, 100000, 1000000]) common.submit(result, expected=210)
''' 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. ''' import common # "last ten digits" = "give me the result mod 10**10" # since addition and exponentiation work under modular arithmetic, just do # all the work mod 10**10 def euler048(n, modulus=None): result = sum([pow(i, i, modulus) for i in range(1, n+1)]) if modulus: result %= modulus return result common.assertEquals(10405071317, euler048(10)) common.submit(euler048(1000, 10**10), expected=9110846700)
the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? ''' import common import itertools data = file("p042.txt") words = [word.strip('"') for word in data.readline().split(",")] max_word_length = max(len(w) for w in words) max_word_score = max_word_length * 26 triangles = set( itertools.takewhile(lambda x: x < max_word_score, (n * (n + 1) / 2 for n in itertools.count()))) def triangle_word(w): return common.wordvalue(w) in triangles common.assertEquals(True, triangle_word('SKY')) count = sum(1 for w in words if triangle_word(w)) common.submit(count, expected=162)
70 - 22 = 48, is not pentagonal. Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk - Pj| is minimised; what is the value of D? ''' import common import itertools def pentagonal(n): return n * (3 * n - 1) / 2 common.assertEquals([1, 5, 12, 22, 35, 51, 70, 92, 117, 145], map(pentagonal, range(1, 11))) max_pentagonal = 0 cached_pentagonals = set() def is_pentagonal(p): global max_pentagonal, cached_pentagonals while max_pentagonal < p: max_pentagonal = pentagonal(len(cached_pentagonals) + 1) cached_pentagonals.add(max_pentagonal) return p in cached_pentagonals common.assertEquals(True, is_pentagonal(92)) common.assertEquals(False, is_pentagonal(91))
''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? ''' import common def largest_prime_factor(n): return common.factor(n)[-1] common.assertEquals(29, largest_prime_factor(13195)) common.submit(largest_prime_factor(600851475143), expected=6857) # command-line utility import sys for arg in sys.argv[1:]: print '%d = %s' % (int(arg), common.factor(int(arg)))
644 = 2^2 * 7 * 23 645 = 3 * 5 * 43 646 = 2 * 17 * 19. Find the first four consecutive integers to have four distinct prime factors. What is the first of these numbers? ''' import collections import common import itertools def distinct_prime_factors(n): return collections.Counter(common.factor(n)).keys() common.assertEquals([2, 7], sorted(distinct_prime_factors(14))) common.assertEquals([3, 5], sorted(distinct_prime_factors(15))) common.assertEquals([2, 7, 23], sorted(distinct_prime_factors(644))) common.assertEquals([3, 5, 43], sorted(distinct_prime_factors(645))) common.assertEquals([2, 17, 19], sorted(distinct_prime_factors(646))) def euler047(n): result = [] for i in itertools.count(2): if len(distinct_prime_factors(i)) == n: result.append(i) if len(result) == n: return result[0] else: result = []
if i >= len(data): return 0 return data[i][j] + max(euler018_brute(data, i + 1, j), euler018_brute(data, i + 1, j + 1)) @common.memoized def euler018_memoized(data, i=0, j=0): '''Just memoize the brute force solution. This is awkward, because the data itself has to be stored with each memoized call. :( ''' if i >= len(data): return 0 return data[i][j] + max(euler018_memoized(data, i + 1, j), euler018_memoized(data, i + 1, j + 1)) # Which algorithm to use: euler018 = euler018_dp TEST_DATA = parse(''' 3 7 4 2 4 6 8 5 9 3 ''') common.assertEquals(23, euler018(TEST_DATA)) common.submit(euler018(DATA), expected=1074)
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. ''' import common def sum_proper_divisors(n): return sum(common.divisors(n)) - n common.assertEquals(284, sum_proper_divisors(220)) common.assertEquals(220, sum_proper_divisors(284)) def amicable(n): other = sum_proper_divisors(n) return n != other and sum_proper_divisors(other) == n common.assertEquals(True, amicable(220)) common.assertEquals(True, amicable(284)) common.assertEquals(False, amicable(12)) # perfect numbers are not amicable with themselves common.assertEquals(False, amicable(6))
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ... 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 T285 = P165 = H143 = 40755. Find the next triangle number that is also pentagonal and hexagonal. ''' import common import itertools def triangles(): for n in itertools.count(1): yield n*(n+1)/2 common.assertEquals([1, 3, 6, 10, 15], list(itertools.islice(triangles(), 5))) def pentagons(): for n in itertools.count(1): yield n*(3*n-1)/2 common.assertEquals([1, 5, 12, 22, 35], list(itertools.islice(pentagons(), 5))) def hexagons(): for n in itertools.count(1): yield n*(2*n-1) common.assertEquals([1, 6, 15, 28, 45], list(itertools.islice(hexagons(), 5))) def tripentahexas(): ts, ps, hs = triangles(), pentagons(), hexagons() t, p, h = ts.next(), ps.next(), hs.next()
0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000 ''' import common import itertools def sequence(): for i in itertools.count(1): for d in str(i): yield int(d) def euler040(indices): return common.product( d for i,d in enumerate(itertools.islice(sequence(), max(indices))) if i+1 in indices) common.assertEquals(1, euler040([12])) result = euler040([1, 10, 100, 1000, 10000, 100000, 1000000]) common.submit(result, expected=210)
''' A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. ''' import common def euler026(limit): return max((len(common.fraction(1, d)[1]),d) for d in range(2,limit+1))[1] common.assertEquals(7, euler026(10)) common.submit(euler026(1000), expected=983)
''' Starting in the top left corner of a 2*2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20*20 grid? ''' import common import math def euler015(n): return math.factorial(2*n) / math.factorial(n)**2 common.assertEquals(6, euler015(2)) common.submit(euler015(20), expected=137846528820)
8208 = 8^4 + 2^4 + 0^4 + 8^4 9474 = 9^4 + 4^4 + 7^4 + 4^4 As 1 = 1^4 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. ''' import common import itertools def solution_length(power): # find out how many digits could be in the solution: for digits in itertools.count(1): if len(str(9**power * digits)) < digits: # if all 9's can't reach the digit count, we've gone too far return digits-1 assertEquals(True, 4 <= solution_length(4)) # example numbers have 4 digits def euler030(power): return sum(i for i in xrange(2, 9**power * solution_length(power)) if sum([int(x)**power for x in str(i)]) == i) return total common.assertEquals(19316, euler030(4)) common.submit(euler030(5), expected=443839)
197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? ''' import common def circular(n): s = str(n) if len(s) > 1: for c in s: if c not in ['1', '3', '7', '9']: return False for i in range(len(s)): if not common.prime(int(s[i:] + s[:i])): return False return True def euler035(limit): return len([i for i in range(limit) if circular(i)]) common.assertEquals(13, euler035(100)) common.submit(euler035(10**6), expected=55)
one in value, and containing two digits in the numerator and denominator. If the product of these four fractions is given in its lowest common terms, find the value of the denominator. ''' import common def cancels(n1, d1, n2, d2): left = common.fraction(n1, d1) right = common.fraction(n2, d2) return left == right and left is not None common.assertEquals(True, cancels(49, 98, 4, 8)) n = 1 d = 1 for a in range(10): for b in range(10): for c in range(1, 10): if cancels(10 * a + c, b + 10 * c, a, b): print 'found a curious fraction: %d%d/%d%d = %d/%d' % (a, c, c, b, a, b) n *= a d *= b print 'product of curious fractions: %d/%d' % (n, d) gcd = common.gcd(n, d)
There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator. If the product of these four fractions is given in its lowest common terms, find the value of the denominator. ''' import common def cancels(n1, d1, n2, d2): left = common.fraction(n1, d1) right = common.fraction(n2, d2) return left == right and left is not None common.assertEquals(True, cancels(49,98, 4,8)) n = 1 d = 1 for a in range(10): for b in range(10): for c in range(1,10): if cancels(10*a + c, b + 10*c, a, b): print 'found a curious fraction: %d%d/%d%d = %d/%d' %(a,c,c,b,a,b) n *= a d *= b print 'product of curious fractions: %d/%d' % (n,d) gcd = common.gcd(n,d) n /= gcd
''' 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, 5 C 3 = 10. In general, n C r = n! / (r!(n-r)!), where r <= n, n! = n*(n-1)*...*3*2*1, and 0! = 1. It is not until n = 23, that a value exceeds one-million: 23 C 10 = 1144066. How many, not necessarily distinct, values of nCr, for 1 <= n <= 100, are greater than one-million? ''' import math import common def c(n,r): return math.factorial(n) / math.factorial(r) / math.factorial(n-r) common.assertEquals(c(23,10), 1144066) result = sum(1 for n in xrange(1, 101) for r in xrange(0, n+1) if c(n,r) > 10**6) common.submit(result, expected=4075)
equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. ''' import common abundant = [x for x in xrange(1,28123) if sum(common.divisors(x)) > 2*x] common.assertEquals(12, abundant[0]) can_be = set(a+b for a in abundant for b in abundant if a <= b and a+b <= 28123) common.assertEquals(24, min(can_be)) cannot_be = [i for i in range(1,28123) if i not in can_be] common.submit(sum(cannot_be), expected=4179871)
''' The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) ''' import common def double_palindrome(n): return common.palindrome(n) and common.palindrome(bin(n)[2:]) common.assertEquals(True, double_palindrome(585)) common.assertEquals(False, double_palindrome(575)) total = sum(i for i in xrange(1000000) if double_palindrome(i)) common.submit(total, expected=872187)
terms = [x] tail = 0 while x != 1: if x in cache: tail = cache[x] break if x % 2: x = 3*x + 1 else: x = x/2 terms.append(x) for i,t in enumerate(terms): cache[t] = len(terms) - i + tail return len(terms) + tail common.assertEquals(10, threen(13)) def euler014(limit): length, start = max((threen(i),i) for i in range(1,limit)) # print "(The path from %d to 1 contains %d term(s))" % (start, length) return start common.assertEquals(9, euler014(10)) # alternate approach, turns out to be too slow: def reverse_threen(limit): needed = set(range(2,limit)) seen = set([1]) distance = {1:set([1])} while needed: d = max(distance.keys())
divisors? ''' import common import itertools def euler012(num_divisors): for n in itertools.count(1): # the formula for the nth triangle number is n*(n+1)/2. # # n and n+1 must be mutually prime, one of them must be even, and # they will still be mutually prime after the even one has been divided # by 2. # # if a*b=c, and a,b are mutually prime, then # num_divisors(c) = num_divisors(a) * num_divisors(b) # The latter is faster to compute. # # So, the nth triangle number is known to be a product of two mutually prime # factors which enable us to compute its divisor count more quickly. if n % 2: divisors = common.num_divisors((n+1)/2) * common.num_divisors(n) else: divisors = common.num_divisors(n+1) * common.num_divisors(n/2) if divisors > num_divisors: return n*(n+1)/2 common.assertEquals(28, euler012(5)) common.submit(euler012(500), expected=76576500)
''' Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. ''' '''Fibonacci numbers, starting from 1,2,3...''' import common import itertools def sum_even_fibs_until(limit): return sum( filter(lambda x: x % 2 == 0, itertools.takewhile(lambda x: x <= limit, common.fibs()))) common.assertEquals(0, sum_even_fibs_until(1)) common.assertEquals(2, sum_even_fibs_until(2)) common.assertEquals(2, sum_even_fibs_until(3)) common.assertEquals(2, sum_even_fibs_until(7)) common.assertEquals(10, sum_even_fibs_until(8)) common.assertEquals(10, sum_even_fibs_until(9)) common.submit(sum_even_fibs_until(4 * 10**6), expected=4613732)
''' The four adjacent digits in the 1000-digit number that have the greatest product are 9*9*8*9 = 5832. Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? ''' DIGITS = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450" import common def euler008(num_digits): # TODO(durandal): rolling window, split by '0' return max(common.product([int(d) for d in DIGITS[i:i+num_digits]]) for i in range(len(DIGITS) - num_digits)) common.assertEquals(5832, euler008(4)) common.submit(euler008(13), expected=23514624000)
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? ''' import common def euler007(n): return common.nth_prime(n-1) # nth_prime is 0-indexed common.assertEquals(13, euler007(6)) common.submit(euler007(10001), expected=104743)
''' Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 * 53 = 49714. What is the total of all the name scores in the file? ''' import common names = [word.strip('"') for word in file('p022.txt').readline().split(',')] names.sort() common.assertEquals('COLIN', names[938-1]) def score(index, name): return common.wordvalue(name) * (index+1) common.assertEquals(49714, score(938-1, 'COLIN')) total_score = sum(score(i, name) for i, name in enumerate(names)) common.submit(total_score, expected=871198282)
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' import common def euler001(limit): return sum(i for i in range(limit) if not i % 3 or not i % 5) common.assertEquals(23, euler001(10)) common.submit(euler001(1000), expected=233168)
import common import itertools def euler012(num_divisors): for n in itertools.count(1): # the formula for the nth triangle number is n*(n+1)/2. # # n and n+1 must be mutually prime, one of them must be even, and # they will still be mutually prime after the even one has been divided # by 2. # # if a*b=c, and a,b are mutually prime, then # num_divisors(c) = num_divisors(a) * num_divisors(b) # The latter is faster to compute. # # So, the nth triangle number is known to be a product of two mutually prime # factors which enable us to compute its divisor count more quickly. if n % 2: divisors = common.num_divisors( (n + 1) / 2) * common.num_divisors(n) else: divisors = common.num_divisors(n + 1) * common.num_divisors(n / 2) if divisors > num_divisors: return n * (n + 1) / 2 common.assertEquals(28, euler012(5)) common.submit(euler012(500), expected=76576500)
''' Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: 2^2=4, 2^3=8, 2^4=16, 2^5=32 3^2=9, 3^3=27, 3^4=81, 3^5=243 4^2=16, 4^3=64, 4^4=256, 4^5=1024 5^2=25, 5^3=125, 5^4=625, 5^5=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by a^b for 2 <= a <= 100 and 2 <= b <= 100? ''' import common def euler029(limit): r = range(2, limit + 1) return len(set(a**b for a in r for b in r)) common.assertEquals(15, euler029(5)) common.submit(euler029(100), expected=9183)
''' import common import itertools def goldbach(n): assert n % 2 == 1 for i in itertools.count(): if common.prime(n - 2 * i * i): return True if 2 * i * i > n: return False common.assertEquals(True, goldbach(9)) common.assertEquals(True, goldbach(15)) common.assertEquals(True, goldbach(21)) common.assertEquals(True, goldbach(25)) common.assertEquals(True, goldbach(27)) common.assertEquals(True, goldbach(33)) common.assertEquals(True, goldbach(7)) # it works for primes too! ^_^ # TODO(goldbach): think of a False test case def euler046(): for n in itertools.count(3, 2): if not goldbach(n): return n
The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. ''' import common import itertools def solution_length(power): # find out how many digits could be in the solution: for digits in itertools.count(1): if len(str(9**power * digits)) < digits: # if all 9's can't reach the digit count, we've gone too far return digits - 1 assertEquals(True, 4 <= solution_length(4)) # example numbers have 4 digits def euler030(power): return sum(i for i in xrange(2, 9**power * solution_length(power)) if sum([int(x)**power for x in str(i)]) == i) return total common.assertEquals(19316, euler030(4)) common.submit(euler030(5), expected=443839)
if start >= prev_end: meeting_count += 1 prev_start = start prev_end = end else: break return meeting_count if __name__ == '__main__': # day1 meetings consist of the following meetings # 0am to 1am, 1am to 2, 2 to 3, 3 to 5 and 4 to 5 day1_meetings = [ [0, 1], [1, 2], [2, 3], [3, 5], [4, 5] ] day1_consecutive = answer(day1_meetings) assertEquals(day1_consecutive, 4, 'four meetings') # day2 meetings day2_meetings = [ [0, 1000000], [42, 43], [0, 1000000], [42, 43] ] day2_consecutive = answer(day2_meetings) assertEquals(day2_consecutive, 1, 'one meeting')
''' n! means n * (n - 1) * ... * 3 * 2 * 1 For example, 10! = 10 * 9 * ... * 3 * 2 * 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! ''' import common import math def euler020(n): return sum(int(d) for d in str(math.factorial(n))) common.assertEquals(27, euler020(10)) common.submit(euler020(100), expected=648)
''' A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a**2 + b**2 = c**2 For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ''' import common def find_triple(desired_sum): for a in range(1, desired_sum): for b in range(a + 1, desired_sum - a): c = desired_sum - a - b if a*a + b*b == c*c: return a*b*c common.assertEquals(3*4*5, find_triple(12)) common.submit(find_triple(1000), expected=31875000)
All the elements are of the array are equal now, and you've got a strategy to report back to Beta Rabbit! Note that if the array was [1,2], the maximum possible number of equal elements we could get is 1, as the cars could never have the same number of rabbits in them. Write a function answer(x), which takes the array of integers x and returns the maximum number of equal array elements that we can get, by doing the above described command as many times as needed. The number of cars in the train (elements in x) will be at least 2, and no more than 100. The number of rabbits that want to share a car (each element of x) will be an integer in the range [0, 1000000]. """ def answer(x): total = sum(x) length = len(x) if (total < length): return total elif (total % length == 0): return length else: return length - 1 if __name__ == '__main__': assertEquals(answer([1, 4, 1]), 3) assertEquals(answer([1, 2]), 1) assertEquals(answer([1, 0]), 1) assertEquals(answer([0, 0, 0]), 0) assertEquals(answer([1, 0, 20]), 3) assertEquals(answer([3, 3, 1000000]), 2) assertEquals(answer([3, 3, 1000000, 22]), 4) assertEquals(answer([2, 2, 2, 1, 1, 1]), 5)
''' Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. ''' '''Fibonacci numbers, starting from 1,2,3...''' import common import itertools def sum_even_fibs_until(limit): return sum(filter(lambda x: x % 2 == 0, itertools.takewhile(lambda x: x <= limit, common.fibs()))) common.assertEquals(0, sum_even_fibs_until(1)) common.assertEquals(2, sum_even_fibs_until(2)) common.assertEquals(2, sum_even_fibs_until(3)) common.assertEquals(2, sum_even_fibs_until(7)) common.assertEquals(10, sum_even_fibs_until(8)) common.assertEquals(10, sum_even_fibs_until(9)) common.submit(sum_even_fibs_until(4 * 10**6), expected=4613732)
''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? ''' import common def largest_prime_factor(n): return common.factor(n)[-1] common.assertEquals(29, largest_prime_factor(13195)) common.submit(largest_prime_factor(600851475143), expected=6857) # command-line utility import sys for arg in sys.argv[1:]: print '%d = %s' % ( int(arg), common.factor(int(arg)))
2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? ''' import common def circular(n): s = str(n) if len(s) > 1: for c in s: if c not in ['1', '3', '7', '9']: return False for i in range(len(s)): if not common.prime(int(s[i:] + s[:i])): return False return True def euler035(limit): return len([i for i in range(limit) if circular(i)]) common.assertEquals(13, euler035(100)) common.submit(euler035(10**6), expected=55)
rational_coefficients = [ fractions.Fraction(c).limit_denominator() for c in coefficients ] print rational_coefficients result = lambda size: sum( size**p * c for p, c in enumerate(reversed(rational_coefficients))) for x in test: assert result(x) == f(x) return result # The antidiagonal is in a different location depending on the parity of size, so don't expect # the same formula to hold for both odd and even sizes. euler028_odd = find_closed_form(euler028, [1, 3, 5, 7], [9]) euler028_even = find_closed_form(euler028, [2, 4, 6, 8], [10]) euler028 = lambda size: [euler028_even, euler028_odd][size % 2](size) common.assertEquals(101, euler028(5)) common.submit(euler028(1001), expected=669171001) # Just showing off; given a closed form, these are essentially free to compute: print euler028(1000000) print euler028(1000001) print euler028(1000000000) print euler028(1000000001) print euler028(1000000000000) print euler028(1000000000001) print euler028(1000000000000000) print euler028(1000000000000001)
4: "forty", 5: "fifty", 6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety" }[x / 10] + pronounce(x % 10) if x < 1000: if x % 100: return pronounce(x / 100) + "hundredand" + pronounce(x % 100) else: return pronounce(x / 100) + "hundred" return "onethousand" def letters_used(x): return len(pronounce(x)) common.assertEquals(23, letters_used(342)) common.assertEquals(20, letters_used(115)) def euler017(limit): return sum(letters_used(i) for i in range(1, limit + 1)) common.assertEquals(19, euler017(5)) common.submit(euler017(1000), expected=21124)
''' Problem statement. ''' import common def euler000(): pass # implementation common.assertEquals(None, euler000()) # example test case common.submit(euler000(), expected=None) # final submission, with post-hoc test
-79 and 1601, is -126479. Considering quadratics of the form: n^2 + an + b, where |a| < 1000 and |b| < 1000 where |n| is the modulus/absolute value of n e.g. |11| = 11 and |-4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. ''' import common import itertools def consecutive_primes(a, b): for n in itertools.count(): if not common.prime(n * n + a * n + b): return n common.assertEquals(40, consecutive_primes(1, 41)) common.assertEquals(80, consecutive_primes(-79, 1601)) result = max((consecutive_primes(a, b), a * b) for a in xrange(-1000, 1000) for b in xrange(-1000, 1000))[1] common.submit(result, expected=-59231)
''' The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. ''' import common import itertools def sum_primes_below(n): return sum(itertools.takewhile(lambda x: x < n, common.primes())) common.assertEquals(17, sum_primes_below(10)) common.submit(sum_primes_below(2000000), expected=142913828922)
''' 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included. ''' import common import math def curious(n): return sum(math.factorial(int(d)) for d in str(n)) == n common.assertEquals(True, curious(145)) common.assertEquals(False, curious(144)) all_curious = [i for i in range(10, 50000) if curious(i)] print all_curious common.submit(sum(all_curious), expected=40730)
''' The four adjacent digits in the 1000-digit number that have the greatest product are 9*9*8*9 = 5832. Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? ''' DIGITS = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450" import common def euler008(num_digits): # TODO(durandal): rolling window, split by '0' return max( common.product([int(d) for d in DIGITS[i:i + num_digits]]) for i in range(len(DIGITS) - num_digits)) common.assertEquals(5832, euler008(4)) common.submit(euler008(13), expected=23514624000)
['K', 'L', 'P', 'D'], ['K', 'J', 'N', 'R'], ] for sublist in matrix: for i in sublist: if word_array[-1] == i: word_array.pop() if len(word_array) == 0: return True return False assertEquals(wordmatch('ARK'), True, 'matched word') assertEquals(wordmatch('RIRL'), False, 'did not matched word') ''' Anagram ''' def agram(word, word2): a = list(word) a.sort() b = list(word2) b.sort() return a == b
''' Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: 2^2=4, 2^3=8, 2^4=16, 2^5=32 3^2=9, 3^3=27, 3^4=81, 3^5=243 4^2=16, 4^3=64, 4^4=256, 4^5=1024 5^2=25, 5^3=125, 5^4=625, 5^5=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by a^b for 2 <= a <= 100 and 2 <= b <= 100? ''' import common def euler029(limit): r = range(2,limit+1) return len(set(a**b for a in r for b in r)) common.assertEquals(15, euler029(5)) common.submit(euler029(100), expected=9183)
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 - 22 = 48, is not pentagonal. Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk - Pj| is minimised; what is the value of D? ''' import common import itertools def pentagonal(n): return n * (3*n - 1) / 2 common.assertEquals([1, 5, 12, 22, 35, 51, 70, 92, 117, 145], map(pentagonal, range(1,11))) max_pentagonal = 0 cached_pentagonals = set() def is_pentagonal(p): global max_pentagonal, cached_pentagonals while max_pentagonal < p: max_pentagonal = pentagonal(len(cached_pentagonals)+1) cached_pentagonals.add(max_pentagonal) return p in cached_pentagonals common.assertEquals(True, is_pentagonal(92)) common.assertEquals(False, is_pentagonal(91)) def euler044(): for i in itertools.count(1):