Prime digit replacements

Problem 51

By replacing the 1st digit of the 2-digit number *3, it turns out that six of the nine possible values: $13, 23, 43, 53, 73$, and $83$, are all prime.

By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding the family: $56003, 56113, 56333, 56443, 56663, 56773$, and $56993$. Consequently $56003$, being the first member of this family, is the smallest prime with this property.

Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.


In [28]:
from euler import Seq, timer, primes, is_prime

def p051():    
    def groups(n):
        return ([[int(str(n).replace(x,y)) for y in '0123456789']
                 >> Seq.toSet 
                 >> Seq.filter(is_prime) 
                 >> Seq.toList
                for x in '0123456789']
                >> Seq.filter(lambda s: (s >> Seq.length) == 8))

    return (primes()
            >> Seq.skipWhile(lambda x: x < 100000)
            >> Seq.collect(groups)
            >> Seq.nth(1)
            >> Seq.min)

timer(p051)


result: 121313 (3.78s)

Permuted multiples

Problem 52

It can be seen that the number, $125874$, and its double, $251748$, contain exactly the same digits, but in a different order.

Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.


In [34]:
from euler import Seq, timer

def p052():
    digits = lambda n: str(n) >> Seq.toSet

    def same_multiples(n):
        sets = range(1,7) >> Seq.map(lambda m: digits(n*m)) >> Seq.toList
        if (sets[1:] >> Seq.forall(lambda x: x==sets[0])):
            return n
        else:
            return None

    return(
        xrange(100000, 1000000)
        >> Seq.map(same_multiples)
        >> Seq.find(lambda n: n is not None))

timer(p052)


result: 142857 (1.01s)

Combinatoric selections

Problem 53

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, $^5C_3=10$.

In general,

$^nC_r = \frac {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 $^nC_r$, for $1 ≤ n ≤ 100$, are greater than one-million?


In [67]:
from euler import Seq, memoize, timer
from math import log

@memoize
def log_factorial(n):
    return xrange(1, n+1) >> Seq.sumBy(log)

log_combinations = lambda n,r: log_factorial(n) - log_factorial(r) - log_factorial(n-r)

def p053():
    cnt = 0
    for n in xrange(1,101):
        for r in xrange(1,n):
            if log_combinations(n,r) > log(1000000):
                cnt += 1
    return cnt

timer(p053)


result: 4075 (0.01s)

Poker hands

Problem 54

In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:

  • High Card: Highest value card.
  • One Pair: Two cards of the same value.
  • Two Pairs: Two different pairs.
  • Three of a Kind: Three cards of the same value.
  • Straight: All cards are consecutive values.
  • Flush: All cards of the same suit.
  • Full House: Three of a kind and a pair.
  • Four of a Kind: Four cards of the same value.
  • Straight Flush: All cards are consecutive values of same suit.
  • Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.

The cards are valued in the order:
2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.

If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on.

Consider the following five hands dealt to two players:

Hand Player 1 Player 2 Winner
1 5H 5C 6S 7S KD
Pair of Fives

 2C 3S 8S 8D TD
Pair of Eights
 Player 2
2 5D 8C 9S JS AC
Highest card Ace
 2C 5C 7D 8S QH
Highest card Queen
 Player 1
3 2D 9C AS AH AC
Three Aces
 3D 6D 7D TD QD
Flush with Diamonds
 Player 2
4 4D 6S 9H QH QC
Pair of Queens
Highest card Nine
 3D 6D 7H QD QS
Pair of Queens
Highest card Seven
 Player 1
5 2H 2D 4C 4D 4S
Full House
With Three Fours
 3C 3D 3S 9S 9D
Full House
with Three Threes
 Player 1

The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner.

How many hands does Player 1 win?


In [100]:
from euler import timer
from collections import Counter

def p054():
    values = {r:i for i,r in enumerate('23456789TJQKA', start=2)}
    straights = [(v, v-1, v-2, v-3, v-4) for v in range(14, 5, -1)] + [(14, 5, 4, 3, 2)]

    ranks = [(1,1,1,1,1), # 0:high card
             (2,1,1,1),   # 1:pair
             (2,2,1),     # 2:two pairs
             (3,1,1),     # 3:3 of a kind
             (),          # 4:straight
             (),          # 5:flush
             (3,2),       # 6:full house
             (4,1)        # 7:four of a kind
                          # 8:straight flush
            ]

    def hand_rank(hand):
        score = zip(*sorted(((v, values[k]) for
                k,v in Counter(x[0] for x in hand).items()), reverse=True))
        rank = ranks.index(score[0])
        if len(set(card[1] for card in hand)) == 1: 
            rank = 5  # flush
        if score[1] in straights:
            rank = 8 if rank == 5 else 4  # straight/straight flush
        return (rank, score[1])
    
    hands = (line.split() for line in open("data/p054.txt"))

    return sum(hand_rank(hand[:5]) > hand_rank(hand[5:]) for hand in hands)
    
timer(p054)


result: 376 (0.04s)

Lychrel numbers

Problem 55

If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.

Not all numbers produce palindromes so quickly. For example,

$$349 + 943 = 1292$$$$1292 + 2921 = 4213$$$$4213 + 3124 = 7337$$

That is, $349$ took three iterations to arrive at a palindrome.

Although no one has proved it yet, it is thought that some numbers, like $196$, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, $10677$ is the first number to be shown to require over fifty iterations before producing a palindrome: $4668731596684224866951378664$ (53 iterations, 28-digits).

Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is $4994$.

How many Lychrel numbers are there below ten-thousand?


In [138]:
from euler import Seq, timer

def p055():
    rev = lambda n: int(str(n)[::-1])
    is_palindrome = lambda n: n == rev(n)
    def is_lychrel(n):
        i, a = 0, n
        while i < 50:
            a += rev(a)
            i += 1 
            if is_palindrome(a): return False
        return True
    return xrange(1,10001) >> Seq.filter(is_lychrel) >> Seq.length

timer(p055)


result: 249 (0.13s)

Powerful digit sum

Problem 56

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?


In [178]:
from euler import timer

def p056():
    digit_sum = lambda a,b: sum(int(x) for x in str(a**b))
    return max(digit_sum(a,b) for a in range(1,100) for b in range(1,100))

timer(p056)


result: 972 (0.52s)

Square root convergents

Problem 57

It is possible to show that the square root of two can be expressed as an infinite continued fraction.

$$√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...$$

By expanding this for the first four iterations, we get:

$$1 + 1/2 = 3/2 = 1.5$$$$1 + 1/(2 + 1/2) = 7/5 = 1.4$$$$1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...$$$$1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...$$

The next three expansions are $99/70$, $239/169$, and $577/408$, but the eighth expansion, $1393/985$, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.

In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?


In [232]:
from euler import Seq, timer
from fractions import Fraction

def p057():
    
    digits = lambda n: len(str(n))

    def series():
        n = Fraction(1)
        while True:
            n = 1 + 1/(1+n)
            yield n
        
    return(
        series() 
        >> Seq.take(1000) 
        >> Seq.filter(lambda n: digits(n.numerator) > digits(n.denominator)) 
        >> Seq.length)

timer(p057)


result: 153 (0.55s)

Spiral primes

Problem 58

Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.

37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18  5  4  3 12 29
40 19  6  1  2 11 28
41 20  7  8  9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49

It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.

If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?


In [236]:
from euler import Seq, timer, is_prime

def p058():
    primes, total, size = 0, 1, 3
    while True:
        primes += (range(4) 
                   >> Seq.map(lambda n: size*size - n*(size-1)) 
                   >> Seq.filter(is_prime) 
                   >> Seq.length)
        total += 4
        if primes * 10 < total: break
        size += 2        
    return size
    
timer(p058)


result: 26241 (15.31s)

XOR decryption

Problem 59

Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.

A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.

For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message.

Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable.

Your task has been made easy, as the encryption key consists of three lower case characters. Using cipher1.txt (right click and 'Save Link/Target As...'), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text.


In [433]:
from euler import Seq, timer
import string
from operator import add
from itertools import product

def p059():

    cipher_text = open('data/p059.txt').read().split(',') >> Seq.map(int) >> Seq.toList
    printable_chars = [ord(c) for c in string.printable]
    is_valid_char =  lambda c: c in printable_chars

    def try_decipher(encrypted, key):
        decrypted = (encrypted 
                     >> Seq.mapi(lambda (i,b): b^key[i%len(key)])
                     >> Seq.toList)
        if (decrypted >> Seq.forall(is_valid_char)):
            msg = decrypted >> Seq.map(chr) >> Seq.reduce(add)
            return sum(decrypted) if ' the ' in msg else None
        else:
            None
        
    return (
        product(range(97,123),range(97,123),range(97,123))
        >> Seq.map(bytearray)
        >> Seq.map(lambda key: try_decipher(cipher_text, key))
        >> Seq.find(lambda x: x is not None))  

timer(p059)


result: 107359 (3.08s)

Prime pair sets

Problem 60

The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.

Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.


In [81]:
from euler import Seq, timer, prime, PrimeQ, PrimePi, is_prime

def p060():
    test_pair = lambda a,b: is_prime(int(str(a) + str(b))) and is_prime(int(str(b) + str(a)))

    # assuming answer will be under 10k
    max_n = PrimePi(10000)

    init = [([prime(a)], a) for a in range(4,max_n+1)]

    next = lambda (prior, a): (range(a+1, max_n+1)
                               >> Seq.map(lambda b: ([prime(b)] + prior, b))
                               >> Seq.filter(lambda (s,_): s[1:] 
                                             >> Seq.forall(lambda x: test_pair(s[0], x))))

    return (init
            >> Seq.collect(next)
            >> Seq.collect(next)
            >> Seq.collect(next)
            >> Seq.collect(next)
            >> Seq.head
            >> Seq.head
            >> Seq.sum)
    
timer(p060)


result: 26033 (38.19s)