Amicable numbers

Problem 21

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

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.


In [1]:
from euler import timer, Seq
from math import sqrt

def d(n):
    return (range(2, int(sqrt(n))+1)
             >> Seq.filter (lambda x: n%x == 0)
             >> Seq.map (lambda x: x if x*x == n else n/x + x)
             >> Seq.sum) + 1

def isAmicable(a):
    b = d(a)
    return (a == d(b)) and (a <> b)

def p021():
    return (range(1, 10001)
             >> Seq.filter(isAmicable)
             >> Seq.sum)

timer(p021)


result: 31626 (0.43s)

Names scores

Problem 22

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?


In [2]:
from euler import timer, Seq

def score(s): 
    return s >> Seq.map(lambda x: ord(x) - 64) >> Seq.sum
    
def p022():
    return (
        open('data/p022.txt').read().split(',')
        >> Seq.map(lambda x: x.strip('"'))
        >> Seq.sort
        >> Seq.mapi(lambda (i,x): score(x)*(i+1))
        >> Seq.sum)

timer(p022)


result: 871198282 (0.04s)

Non-abundant sums

Problem 23

A perfect number is a number for which the sum of its proper divisors is exactly 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.


In [3]:
from euler import FactorInteger, Seq, timer
from operator import mul

def divisor_sum(n):
    return (
        FactorInteger(n) 
        >> Seq.map(lambda (p,a): (p**(a+1) - 1)/(p-1)) 
        >> Seq.reduce(mul)
        ) - n

def p023():
    max_n = 28123
    abundants = range(12, max_n+1) >> Seq.filter(lambda n: n < divisor_sum(n)) >> Seq.toList
    abundant_sums = (abundants 
                     >> Seq.collect(lambda a: abundants  
                                               >> Seq.map(lambda b: a+b)
                                               >> Seq.takeWhile(lambda x: x < (max_n+1)))
                     >> Seq.toSet)
    return max_n * (max_n + 1) / 2 - sum(abundant_sums)

timer(p023)


result: 4179871 (13.92s)

Lexicographic permutations

Problem 24

A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:

012 021 102 120 201 210

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?


In [4]:
from math import factorial
from euler import timer

def p024():
    numbers = range(10)

    def loop(remainder, acc):
        k = len(numbers) - 1
        if k==0:
            return acc + str(numbers[0])
        else:
            next = numbers[remainder / factorial(k)]
            numbers.remove(next)
            return loop((remainder%(factorial(k))),(acc + str(next)))

    return loop(999999,"")

timer(p024)


result: 2783915460 (0.00s)

1000-digit Fibonacci number

Problem 25

The Fibonacci sequence is defined by the recurrence relation:

$F_n = F_{n−1} + F_{n−2}$, where $F_1 = 1$ and $F_2 = 1$. Hence the first 12 terms will be:

$F_1 = 1$
$F_2 = 1$
$F_3 = 2$
$F_4 = 3$
$F_5 = 5$
$F_6 = 8$
$F_7 = 13$
$F_8 = 21$
$F_9 = 34$
$F_{10} = 55$
$F_{11} = 89$
$F_{12} = 144$
The 12th term, $F_{12}$, is the first term to contain three digits.

What is the first term in the Fibonacci sequence to contain 1000 digits?


In [5]:
from math import log10
from euler import timer, Seq

def p025():
    return (
        Seq.unfold(lambda (a,b):(b, (b,a+b)), (0,1)) 
        >> Seq.findIndex(lambda x: log10(x) > 999)
    ) + 1

timer(p025)


result: 4782 (0.01s)

Reciprocal cycles

Problem 26

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.


In [6]:
from euler import timer, Seq

def cycle(denom):
    if denom==2 or denom==5:
        return 0
    elif denom%2==0:
        return cycle(denom/2)
    elif denom%5==0:
        return cycle(denom/5)
    else:
        return (
            Seq.initInfinite(lambda x: x+1)
            >> Seq.map (lambda x: 10 ** x - 1)
            >> Seq.findIndex(lambda x: x%denom==0)
            ) + 1

def p026():
    return range(1, 1001) >> Seq.maxBy(cycle)

timer(p026)


result: 983 (0.30s)

Quadratic primes

Problem 27

Euler discovered the remarkable quadratic formula:

$n^2 + n + 41$

It turns out that the formula will produce $40$ primes for the consecutive values $n = 0$ to $39$. However, when $n = 40$, $40^2 + 40 + 41 = 40(40 + 1) + 41$ is divisible by $41$, and certainly when $n = 41$, $41^2 + 41 + 41$ is clearly divisible by $41$.

The incredible formula $n^2 − 79n + 1601$ was discovered, which produces $80$ primes for the consecutive values $n = 0$ to $79$. The product of the coefficients, $−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$.


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

def primes_generated(x):
    a,b = x
    return (
        Seq.initInfinite(lambda n: n*n + a*n + b)
        >> Seq.takeWhile(is_prime)
        >> Seq.length)

def p027():
        primes_1000 = (primes() 
                       >> Seq.takeWhile(lambda x: x<1000) 
                       >> Seq.toList)
        a,b = ([(a,b) for a in range(-999,1000) 
                      for b in primes_1000]
               >> Seq.maxBy(primes_generated))
        return a*b
               
timer(p027)


result: -59231 (6.55s)

Number spiral diagonals

Problem 28

Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

21 22 23 24 25
20 07 08 09 10
19 06 01 02 11
18 05 04 03 12
17 16 15 14 13

It can be verified that the sum of the numbers on the diagonals is 101.

What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?


In [8]:
from euler import timer

def p028():
    n = 1001

    def collect(depth, start, acc):
        if (depth > n/2):
            return acc
        else:
            return collect(depth+1, start+8*depth, acc+4*start+20*depth)

    return collect(1,1,1)

timer(p028)


result: 669171001 (0.00s)

Distinct powers

Problem 29

Consider all integer combinations of $a^b$ 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$?


In [9]:
from euler import timer

def p029():
    return (set(a **b for a in range(2,101) for b in range(2,101))
             >> Seq.length)

timer(p029)


result: 9183 (0.02s)

Digit fifth powers

Problem 30

Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

$1634 = 1^4 + 6^4 + 3^4 + 4^4$
$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.


In [10]:
from euler import timer

def p030():
    def is_sum(n):
        return (
            str(n)
            >> Seq.map(lambda x: int(x) ** 5)
            >> Seq.sum
        ) == n

    max_n = (
        ((Seq.unfold(lambda x: (x, x+1), 1)
         >> Seq.find(lambda x: 10 ** x - 1 > x * 9 ** 5)
        ) - 1) * 9 ** 5)

    return (
        range(2, max_n + 1)
         >> Seq.filter(is_sum)
         >> Seq.sum)
    
timer(p030)


result: 443839 (2.66s)