HOPE LAM

Project Euler

Question 1

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. Show/Hide Solution

sum = 0
i = 0
while i < 1000:
    if (i%3 == 0) or (i%5 == 0):
        sum += i
    i = i + 1
    
print sum

Question 2

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. Show/Hide Solution

x = 1
y = 1
z = 2
sum = 0
while z < 4000000:
z = x + y
x = y
y = z
print z, x, y
if z%2 == 0:
    sum += z
print sum 

Question 3

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? Show/Hide Solution

def check_if_prime(n):
    if n == 1:
        return False
    if n == 2 or n ==3:
        return True
    if n % 2 == 0:
        return False
    i = 3
    upper_limit = n**.5 
    while i <= upper_limit:
        if n % i == 0:
            return False
        else:
            i += 2
    return True


primefactors = []

i = 3
number = 600851475143
divisor = 600851475143
while i < number**.5:
    if check_if_prime(i) == True:
        while divisor%i == 0:
            divisor /= i
            primefactors.append(i)
    i += 2

print primefactors

Question 4

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. Show/Hide Solution

def isPalindrome(number):
    mylist = []
    mylist = list(str(number))
    i = 0
    while i <= len(mylist)/2:   
        if mylist[i] != mylist[-(i+1)]:
            return False
        i += 1
    return True


palindrome = 9009

a = 100
while a <= 999:
    b = 100
    while b <= 999:
        number = a*b
        if number > palindrome and isPalindrome(number):
            palindrome = number
            print palindrome
        b +=1
    a +=1

Question 6

The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. Show/Hide Solution

i = 100
total = 0
while i > 0:
square = i**2
total = total + square
i = i - 1
sum_of_squares = total
print sum_of_squares

i = 100
other_total = 0
while i > 0:
other_total = other_total + i
i = i - 1
square_of_the_sum = other_total**2
print square_of_the_sum

difference = sum_of_squares - square_of_the_sum
print difference

Question 7

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 10 001st prime number? Show/Hide Solution

def check_if_prime(n):
    if n == 1:
        return False
    if n == 2 or n ==3:
        return True
    if n % 2 == 0:
        return False
    i = 3
    upper_limit = n**.5 
    while i <= upper_limit:
        if n % i == 0:
            return False
        else:
            i += 2
    return True


primelist = []

def find_nth_prime(n):
    i = 1
    while len(primelist) < n:
        if check_if_prime(i) == True:
            primelist.append(i)
        i += 1
    print n, "th prime is equal to", primelist[-1]


find_nth_prime(10001)

Question 8

Find the greatest product of five consecutive digits in the 1000-digit number. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Show/Hide Solution

list = str("7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450")
x = 0
y = 5
highest_product = 0
while y <= 1000:
substr = list[x:y]
product = int(substr[0])*int(substr[1])*int(substr[2])*int(substr[3])*int(substr[4])
if product > highest_product:
highest_product = product
x += 1
y += 1
print highest_product

Question 9

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. Show/Hide Solution

def foo():
    for x in xrange(1, 1000):
        for y in xrange(1, 1000):
            z = 1000 - x - y
            if x * x + y * y == z * z:
                return (x*y*z)

print foo()

Question 10

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. Show/Hide Solution

def check_if_prime(n):
    if n == 1:
        return False
    if n == 2 or n ==3:
        return True
    if n % 2 == 0:
        return False
    i = 3
    upper_limit = n**.5 
    while i <= upper_limit:
        if n % i == 0:
            return False
        else:
            i += 2
    return True


primelist = []

i = 1
while i < 2000000:
    if check_if_prime(i) == True:
        print i
        primelist.append(i)
    i += 1

print "sum is", sum(primelist)

Question 12

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? Show/Hide Solution

def getDivisors(number):
    divisors = []
    i = 1
    while i <= number/2:
        if number % i == 0:
            divisors.append(i)
        i += 1
    return divisors       
      
def getTriangleNumber(number):
    TriangleNumber = 0
    i = number
    while i >= 1:
        TriangleNumber = i + TriangleNumber
        i -= 1
    return TriangleNumber
    
        
i = 1
while True:
    print "length is" , len(getDivisors(getTriangleNumber(i)))
    print getDivisors(getTriangleNumber(i))
    if len(getDivisors(getTriangleNumber(i) > 500:
        break
    i += 1

Question 13

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. 37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 89261670696623633820136378418383684178734361726757 28112879812849979408065481931592621691275889832738 44274228917432520321923589422876796487670272189318 47451445736001306439091167216856844588711603153276 70386486105843025439939619828917593665686757934951 62176457141856560629502157223196586755079324193331 64906352462741904929101432445813822663347944758178 92575867718337217661963751590579239728245598838407 58203565325359399008402633568948830189458628227828 80181199384826282014278194139940567587151170094390 35398664372827112653829987240784473053190104293586 86515506006295864861532075273371959191420517255829 71693888707715466499115593487603532921714970056938 54370070576826684624621495650076471787294438377604 53282654108756828443191190634694037855217779295145 36123272525000296071075082563815656710885258350721 45876576172410976447339110607218265236877223636045 17423706905851860660448207621209813287860733969412 81142660418086830619328460811191061556940512689692 51934325451728388641918047049293215058642563049483 62467221648435076201727918039944693004732956340691 15732444386908125794514089057706229429197107928209 55037687525678773091862540744969844508330393682126 18336384825330154686196124348767681297534375946515 80386287592878490201521685554828717201219257766954 78182833757993103614740356856449095527097864797581 16726320100436897842553539920931837441497806860984 48403098129077791799088218795327364475675590848030 87086987551392711854517078544161852424320693150332 59959406895756536782107074926966537676326235447210 69793950679652694742597709739166693763042633987085 41052684708299085211399427365734116182760315001271 65378607361501080857009149939512557028198746004375 35829035317434717326932123578154982629742552737307 94953759765105305946966067683156574377167401875275 88902802571733229619176668713819931811048770190271 25267680276078003013678680992525463401061632866526 36270218540497705585629946580636237993140746255962 24074486908231174977792365466257246923322810917141 91430288197103288597806669760892938638285025333403 34413065578016127815921815005561868836468420090470 23053081172816430487623791969842487255036638784583 11487696932154902810424020138335124462181441773470 63783299490636259666498587618221225225512486764533 67720186971698544312419572409913959008952310058822 95548255300263520781532296796249481641953868218774 76085327132285723110424803456124867697064507995236 37774242535411291684276865538926205024910326572967 23701913275725675285653248258265463092207058596522 29798860272258331913126375147341994889534765745501 18495701454879288984856827726077713721403798879715 38298203783031473527721580348144513491373226651381 34829543829199918180278916522431027392251122869539 40957953066405232632538044100059654939159879593635 29746152185502371307642255121183693803580388584903 41698116222072977186158236678424689157993532961922 62467957194401269043877107275048102390895523597457 23189706772547915061505504953922979530901129967519 86188088225875314529584099251203829009407770775672 11306739708304724483816533873502340845647058077308 82959174767140363198008187129011875491310547126581 97623331044818386269515456334926366572897563400500 42846280183517070527831839425882145521227251250327 55121603546981200581762165212827652751691296897789 32238195734329339946437501907836945765883352399886 75506164965184775180738168837861091527357929701337 62177842752192623401942399639168044983993173312731 32924185707147349566916674687634660915035914677504 99518671430235219628894890102423325116913619626622 73267460800591547471830798392868535206946944540724 76841822524674417161514036427982273348055556214818 97142617910342598647204516893989422179826088076852 87783646182799346313767754307809363333018982642090 10848802521674670883215120185883543223812876952786 71329612474782464538636993009049310363619763878039 62184073572399794223406235393808339651327408011116 66627891981488087797941876876144230030984490851411 60661826293682836764744779239180335110989069790714 85786944089552990653640447425576083659976645795096 66024396409905389607120198219976047599490197230297 64913982680032973156037120041377903785566085089252 16730939319872750275468906903707539413042652315011 94809377245048795150954100921645863754710598436791 78639167021187492431995700641917969777599028300699 15368713711936614952811305876380278410754449733078 40789923115535562561142322423255033685442488917353 44889911501440648020369068063960672322193204149535 41503128880339536053299340368006977710650566631954 81234880673210146739058568557934581403627822703280 82616570773948327592232845941706525094512325230608 22918802058777319719839450180888072429661980811197 77158542502016545090413245809786882778948721859617 72107838435069186155435662884062257473692284509516 20849603980134001723930671666823555245252804609722 53503534226472524250874054075591789781264330331690 Show/Hide Solution

f = open('raw_question_13.txt', 'rt')

total = 0
for line in f:
num = int(line)
total = total + num
print total

f.close()

Question 14

The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. Show/Hide Solution

winner = 1
length_winner = 1

i = 2
while i < 1000000:
    print i
    n = i
    mylist = [n]
    while n != 1:
        if n % 2 == 0:
            n = n/2
            mylist.append(n)
        else:
            n = 3*n + 1
            mylist.append(n)
    if len(mylist) + 1 > length_winner:
        length_winner = len(mylist) + 1
        winner = mylist[0]
    i += 1

print winner
print length_winner

Question 16

215 = 32768, and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? Show/Hide Solution

i = 2**1000
sum = 0
while i > 0:
num = i % 10
sum = sum + num
i = i / 10
print sum

Question 17

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. Show/Hide Solution

i = 1000
sum = 0
while 1000 >= i >= 1:
# w is for special cases
w = 0
if i == 1000:
w = 11
if i == 10 or i % 100 == 10:
w = 3
if i == 11 or i % 100 == 11:
w = 6 - 3
if i == 12 or i % 100 == 12:
w = 6 - 3
if i == 13 or i % 100 == 13:
w = 8 - 5
if i == 14 or i % 100 == 14:
w = 8 - 4
if i == 15 or i % 100 == 15:
w = 7 - 4
if i == 16 or i % 100 == 16:
w = 7 - 3
if i == 17 or i % 100 == 17:
w = 9 - 5
if i == 18 or i % 100 == 18:
w = 8 - 5
if i == 19 or i % 100 == 19:
w = 8 - 4
if i % 10 == 0:
x = 0 
if i % 10 == 1:
x = 3
if i % 10 == 2:
x = 3
if i % 10 == 3:
x = 5
if i % 10 == 4:
x = 4
if i % 10 == 5:
x = 4
if i % 10 == 6:
x = 3
if i % 10 == 7:
x = 5
elif i % 10 == 8:
x = 5
elif i % 10 == 9:
x = 4
tens_digit = i/10
if tens_digit % 10 == 0:
y = 0 
if tens_digit % 10 == 1:
y = 0 # numbers between 10 and 20 are spelled funky
if tens_digit % 10 == 2:
y = 6
if tens_digit % 10 == 3:
y = 6
if tens_digit % 10 == 4:
y = 5
if tens_digit % 10 == 5:
y = 5
if tens_digit % 10 == 6:
y = 5
if tens_digit % 10 == 7:
y = 7
if tens_digit % 10 == 8:
y = 6
if tens_digit % 10 == 9:
y = 6
hundreds_digit = i/100
if hundreds_digit % 10 == 0:
z = 0 
if hundreds_digit % 10 == 1 and i % 100 == 0:
z = 3 + 7
elif hundreds_digit % 10 == 1:
z = 3 + 10
if hundreds_digit % 10 == 2 and i % 100 == 0:
z = 3 + 7
elif hundreds_digit % 10 == 2:
z = 3 + 10
if hundreds_digit % 10 == 3 and i % 100 == 0:
z = 5 + 7
elif hundreds_digit % 10 == 3: 
z = 5 + 10
if hundreds_digit % 10 == 4 and i % 100 == 0:
z = 4 + 7
elif hundreds_digit % 10 == 4:
z = 4 + 10
if hundreds_digit % 10 == 5 and i % 100 == 0:
z = 4 + 7
elif hundreds_digit % 10 == 5:
z = 4 + 10
if hundreds_digit % 10 == 6 and i % 100 == 0:
z = 3 + 7
elif hundreds_digit % 10 == 6:
z = 3 + 10
if hundreds_digit % 10 == 7 and i % 100 == 0:
z = 5 + 7
elif hundreds_digit % 10 == 7:
z = 5 + 10
if hundreds_digit % 10 == 8 and i % 100 == 0:
z = 5 + 7
elif hundreds_digit % 10 == 8:
z = 5 + 10
if hundreds_digit % 10 == 9 and i % 100 == 0:
z = 4 + 7
elif hundreds_digit % 10 == 9:
z = 4 + 10
sum = sum + w + x + y + z
i = i - 1
print sum

Question 19

You are given the following information, but you may prefer to do some research for yourself.

How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? Show/Hide Solution

thirty_days = [4,6,9,11]
thirtyone_days = [1,3,5,7,8,10,12]
sunday_count = 0
date_count = 2 #starts on 2 because Dec 31, 1900 is a Tuesday
year = 1901
while year < 2001:
month = 1
while month <= 12:
if month == 2:
if year % 400 == 0: date_count = date_count + 29
elif year % 4 == 0 and year % 100 != 0: date_count = date_count + 29
else: date_count = date_count + 28
if month in thirty_days: date_count = date_count + 30
if month in thirtyone_days: date_count = date_count + 31
if date_count % 7 == 0: sunday_count += 1
month += 1 
year += 1
print sunday_count

Question 20

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! Show/Hide Solution

n = 100
def factorial(n):
if n == 1 or n == 0:
return 1
value = n*factorial(n - 1)
return value
     
     
y = str(factorial(n))

sum = 0
for i in y:
sum += int(i)
print sum

Question 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. Show/Hide Solution

def amicable_pair(x):
i = 1
sum_x = 0
while i <= x/2:
if x % i == 0: sum_x = sum_x + i
i += 1

y = sum_x
i = 1
sum_y = 0
while i <= y/2:
if y % i == 0: sum_y = sum_y + i
i += 1

if sum_y == x and x != y: return y
else: return None


i = 0
list_all_amicable = []
sum_all_amicable = 0
while i < 10000:
if amicable_pair(i) != None and i not in list_all_amicable:
sum_all_amicable = sum_all_amicable + i + amicable_pair(i)
list_all_amicable.append(i)
list_all_amicable.append(amicable_pair(i))
i += 1
print sum_all_amicable

Question 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? Show/Hide Solution

rawdata = open("names.txt")
text = rawdata.read()
rawdata.close()

alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

text = text[1:-1]
name_list = sorted(text.split('","'))
sum = 0
for name in name_list:
for letter in name:
sum = sum + (alphabet.index(letter) + 1) * (name_list.index(name) + 1)
print sum

Question 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. Show/Hide Solution

#brute forcing takes a very long time to run the program
#but gets the job done
def list_proper_divisors(num):
    list_of_divisors = []
    
    i = 1
    while i <= num/2:
        if num%i == 0:
            list_of_divisors.append(i)
        i += 1
            
    return list_of_divisors

def is_abundant(num):
    if sum(list_proper_divisors(num)) > num:
        return True
    else: return False


#create a list of abundant nums
abundant_nums = []
i = 1
while i <= 28123:
    if is_abundant(i):
        abundant_nums.append(i)
    i += 1
    
#create a list of nums that are the sum of two abundants
nums_that_are_sum_of_two_abundants = []
for x in abundant_nums:
    for y in abundant_nums:
        z = x + y
        if z < 28123:
            nums_that_are_sum_of_two_abundants.append(z)
        else: break

#Find sum of all the positive integers which 
#cannot be written as the sum of two abundants
my_sum = 0
for i in xrange (1, 28124):
    if i not in nums_that_are_sum_of_two_abundants:
        my_sum += i
        
print my_sum

Question 25

The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: 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? Show/Hide Solution

def fibonacci(n):
if n == 1 or n == 2: return 1
count = 3
x = 1
y = 1
while count <= n:
z = x + y
x = y
y = z
count += 1
return z

i = 1
while len(str(fibonacci(i))) < 1000: 
i += 1
print i

Question 29

Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5: 22=4, 23=8, 24=16, 25=32 32=9, 33=27, 34=81, 35=243 42=16, 43=64, 44=256, 45=1024 52=25, 53=125, 54=625, 55=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 ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100? Show/Hide Solution

foo = {}
for x in xrange(2, 101):
    for y in xrange(2, 101):
        foo[x ** y] = True
print len(foo)

Question 30

Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 14 + 64 + 34 + 44 8208 = 84 + 24 + 04 + 84 9474 = 94 + 44 + 74 + 44 As 1 = 14 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. Show/Hide Solution

def sum_fifth_power_digits(num):
    my_sum = 0
    while num > 0:
        my_sum += (num%10)**5
        num /= 10
    return my_sum 

upperlimit = 9**6 #not sure what the exact upper limit is...
answer = 0
for x in xrange(2, upperlimit):
    if x == sum_fifth_power_digits(x):
        answer += x
        print answer

Question 32

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. Show/Hide Solution

def ispandigital(x, y):
    pandigital = {1:1, 2:1, 3:1, 4:1, 5:1, 6:1, 7:1, 8:1, 9:1}
    xy = x*y
    mystr = str(x) + str(y) + str(xy)
    mydigits = {}
    mylist = []
    for digit in mystr:
        if digit not in mydigits.keys():
            mydigits[digit] = 1
        else: return False
    if mydigits.has_key(str(0)): return False
    for each in mydigits:
        mylist.append(1)
    if len(mylist) == 9:
        return True
    else: return False


products = []
answer = 0
for x in xrange (1, 5000): #5000 upperbound is just a guess
    for y in xrange (1, 5000):
        if ispandigital(x,y):
            if x*y not in products:                
                products.append(x*y)
                answer += (x*y)
                print x, y, x*y, answer
print answer

Question 34

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. Show/Hide Solution

def factorial(n):
if n == 1 or n == 0:
return 1
value = n*factorial(n - 1)
return value

def digit_factorial(num):
    num_list = list(str(num))
    mysum = 0
    for each in num_list:
        mysum += factorial(int(each))
    return mysum


upperbound = factorial(9) #trial upperbound
answer = 0
for x in xrange(3, upperbound):
    if x == digit_factorial(x):
        answer += x
print answer

Question 35

The number, 197, is called a circular prime because all rotations of the digits: 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? Show/Hide Solution

def is_prime(n):
    if n == 1:
        return False
    if n == 2 or n ==3:
        return True
    if n % 2 == 0:
        return False
    i = 3
    upper_limit = n**.5 
    while i <= upper_limit:
        if n % i == 0:
            return False
        else:
            i += 2
    return True
    
def list_of_rotated_digits(n):
    my_list = []
    length = len(str(n))
    my_str = str(n)    
    for x in xrange(length):
        my_new_str = my_str[1:] + my_str[0]
        my_list.append(int(my_new_str))
        my_str = my_new_str
        
    return my_list
        
def is_circular(n): 
    my_list = list_of_rotated_digits(n)
    for x in my_list:
        if is_prime(x) == False: return False
    return True


primelist = []

i = 1
while i < 1000000:
    if is_prime(i) == True:
        primelist.append(i)
    i += 1
    
count = 0
for x in primelist:
    if is_circular(x):
        count += 1
        
print count

Question 36

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.) Show/Hide Solution

def is_palindrome(number):
    mylist = []
    mylist = list(str(number))
    i = 0
    while i <= len(mylist)/2:   
        if mylist[i] != mylist[-(i+1)]:
            return False
        i += 1
    return True

def dec_to_bin(num):
    binary = ''
    while num >= 1:
        if num%2 == 0:
            binary = '0' + binary 
        else: binary = '1' + binary
        num /= 2
    return binary
    
    
palindrome_list = []
double_palindrome_list = []

for x in xrange (1, 1000001):
    if is_palindrome(x):
        palindrome_list.append(x)

for x in palindrome_list:
    if is_palindrome(dec_to_bin(x)):
        double_palindrome_list.append(x)
        
my_sum = 0
for x in double_palindrome_list:
    my_sum += x
    
print my_sum

Question 37

The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. Show/Hide Solution

def isPrime(n):
    if n == 1:
        return False
    if n == 2 or n ==3:
        return True
    if n % 2 == 0:
        return False
    i = 3
    upper_limit = n**.5 
    while i <= upper_limit:
        if n % i == 0:
            return False
        else:
            i += 2
    return True

def isTruncatable(primeNum):
    mystr = str(primeNum)
    while len(mystr) > 1:
        mystr = mystr[1:]
        if isPrime(int(mystr)):
            continue
        else: return False
    
    mystr = str(primeNum)
    while len(mystr) > 1:
        mystr = mystr[:-1]
        if isPrime(int(mystr)):
            continue
        else: return False
    return True
        

primelist = []

i = 1
while i < 1000000: #trial upper limit
    if isPrime(i) == True:
        primelist.append(i)
    i += 1


count = 0
answer = 0
n = 4 #start count at 4 to exclude 2, 3, 5, 7
while count < 11:
    each = primelist[n]
    if isTruncatable(each):
        answer += each
        count += 1
        n += 1
    else: n += 1
    if each == primelist[-1]:
        print "must extend primelist"
        break

print answer

Question 39

If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120. {20,48,52}, {24,45,51}, {30,40,50} For which value of p ≤ 1000, is the number of solutions maximised? Show/Hide Solution

right_triangles = {}

for x in xrange(1, 1001):
    for y in xrange(1, 1001 - x):
        for z in xrange(1, 1001 - x - y):
            if x**2 + y**2 == z**2:
                perimeter = x + y + z
                if perimeter in right_triangles:
                    double = False
                    for i in right_triangles[perimeter]:
                        if i[2] == z:
                            double = True
                    if not double:                            
                        right_triangles[perimeter].append([x, y, z])    

                else:
                    right_triangles[perimeter] = [[x, y, z]]

max_len = 0
max_key = ''
for key in right_triangles:
    if len(right_triangles[key]) > max_len:
        max_len = len(right_triangles[key])
        max_key = key
print max_key

Question 40

An irrational decimal fraction is created by concatenating the positive integers: 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 Show/Hide Solution

z = ''
i = 1
while len(z) < 1000001:
    z += str(i)
    i += 1
    
answer = int(z[0])*int(z[9])*int(z[99])*int(z[999])*int(z[9999])*int(z[99999])*int(z[999999])
print answer

Question 42

The nth term of the sequence of triangle numbers is given by, tn = (1/2)*n*(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, 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? Show/Hide Solution

# convert words to word value
rawdata = open('words.txt')
text = rawdata.read()
rawdata.close()

text = text[1:-1]
word_list = sorted(text.split('","'))

alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

word_value_list = []
for word in word_list:
    word_value = 0
    for letter in word:
        word_value += (alphabet.index(letter) + 1)
    word_value_list.append(word_value)
    
#find the highest word value
max_value = max(word_value_list)

#create a list of triangle numbers where the last t_n is one higher than the highest word value
triangle_nums = []

i = 1
max_tri_num = 1
while max_tri_num < max_value:
    max_tri_num = (.5)*i*(i+1)
    triangle_nums.append(int(max_tri_num))
    i += 1

#count triangle words
count = 0
for num in word_value_list:
    if num in triangle_nums:
        count += 1
print count

Question 45

Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:

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. Show/Hide Solution

def triangle(n):
    return n*(n+1)/2
 
def is_pentagonal(num, N):
    pent = 0
    for n in xrange(1, N):
        while pent <= num:
            pent = n*(3*n-1)/2
            if pent == num:
                return True
            else: break
    return False
  
def is_hexagonal(num, N):
    hexag = 0
    for n in xrange(1, N):
        while hexag <= num:
            hexag = n*(2*n-1)
            if hexag == num:
                return True
            else: break
    return False

i = 286
all_true = False
while not all_true:
    if is_pentagonal(triangle(i), i):
        if is_hexagonal(triangle(i), i):
            answer = triangle(i)
            break
    i += 1

print answer

Question 47

The first two consecutive numbers to have two distinct prime factors are: 14 = 2 × 7 15 = 3 × 5 The first three consecutive numbers to have three distinct prime factors are: 644 = 22 × 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? Show/Hide Solution

#brute forced it. took my computer over two hours.
# it's very redundant. a sieve of eratosthenes would be much better.
def check_if_prime(n):
    if n == 1:
        return False
    if n == 2 or n ==3:
        return True
    if n % 2 == 0:
        return False
    i = 3
    upper_limit = n**.5 
    while i <= upper_limit:
        if n % i == 0:
            return False
        else:
            i += 2
    return True

def distinct_prime_factors(num):   
    dpf = []

    i = 2
    divisor = num
    while i <= num/2:
        if check_if_prime(i) == True:
            while divisor%i == 0:
                divisor /= i
                if i not in dpf:
                    dpf.append(i)
        if i > 2:
            i += 2
        else: i += 1

    return dpf 
    
 
i = 1
four_conseq = False
while not four_conseq:
    #print i
    if len(distinct_prime_factors(i)) ==4:
        if len(distinct_prime_factors(i+1)) == 4:
            if len(distinct_prime_factors(i+2)) == 4:
                if len(distinct_prime_factors(i+3)) == 4:
                    print 'answer = ', i
                    break
    i += 1

Question 48

The series, 11 + 22 + 33 + ... + 1010 = 10405071317. Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000. Show/Hide Solution

my_sum = 0
for i in xrange(1, 1001):
    my_sum += i**i
print 'answer = ', str(my_sum)[-10:]

Question 49

The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. What 12-digit number do you form by concatenating the three terms in this sequence? Show/Hide Solution

# very hacky way, but gets the answer (in backwards order)

#find all primes between 999 and 10000
def check_if_prime(n):
    if n == 1:
        return False
    if n == 2 or n ==3:
        return True
    if n % 2 == 0:
        return False
    i = 3
    upper_limit = n**.5 
    while i <= upper_limit:
        if n % i == 0:
            return False
        else:
            i += 2
    return True

#create prime list
def find_primes(start, stop):
    primelist = []

    i = start
    while i < stop:
        if check_if_prime(i) == True:
            primelist.append(i)
        i += 1
    return primelist

#create a dictionary for each prime with digit as key and occurance as value
def digit_dict(num):
    digit_dict = {}
    
    mylist = [int(i) for i in str(num)]
    
    for digit in mylist:
        if digit in digit_dict:
            digit_dict[digit] += 1
        else: digit_dict[digit] = 1
    
    return digit_dict
            

#create a dictionary with each prime as key and digit_dict(prime) as value    
dict_of_dict = {}
primelist = find_primes(999, 10000)
for prime in primelist:
    dict_of_dict[prime] = digit_dict(prime)

#create a list of lists of prime permutations
list_of_lists = []
for prime in primelist:
    perm_list = []
    for other_prime in primelist: 
        if dict_of_dict[prime] == dict_of_dict[other_prime]:
            perm_list.append(other_prime)
    if len(perm_list) >= 3:
        if perm_list not in list_of_lists:
            list_of_lists.append(perm_list)

#reverse lists so numbers go from high to low
for each_list in list_of_lists:
    each_list.reverse()
    
#go through each of the lists to find the special permutations
answer = {}
for each_list in list_of_lists:
    differences = {}
    for x in each_list[:-1]:
        for y in each_list[(each_list.index(x) + 1):]:
            diff = x - y
            if diff in differences.keys():
                differences[diff].append(y)
                if diff == 3330:
                    answer[diff] = differences[diff]
            else: differences[diff] = [x, y]
print answer[3330][2], answer[3330][1], answer[3330][0]

Question 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. Show/Hide Solution

def digit_dict(num):
    digit_dict = {}
    
    mylist = [int(i) for i in str(num)]
    
    for digit in mylist:
        if digit in digit_dict:
            digit_dict[digit] += 1
        else: digit_dict[digit] = 1
    
    return digit_dict
    
def has_same_digits(num1, num2):
    if digit_dict(num1) == digit_dict(num2):
        return True
    else: return False
    
def answer():
    x = 1
    while True:
        print x
        if has_same_digits(x, 2*x):
            if has_same_digits(x, 3*x):
                if has_same_digits(x, 4*x):
                    if has_same_digits(x, 5*x):
                        if has_same_digits(x, 6*x):
                            return x
        x += 1

print answer()

Question 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? NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers. Show/Hide Solution

def is_palindrome(number):
    mylist = []
    mylist = list(str(number))
    i = 0
    while i <= len(mylist)/2:   
        if mylist[i] != mylist[-(i+1)]:
            return False
        i += 1
    return True
     
def reverse_num(num):
    mylist = []
    mylist = list(str(num))
    
    reverse_num = ''
    for digit in mylist:
        reverse_num = digit + reverse_num
        
    return int(reverse_num)

def is_Lychrel(num):   
    i = 0
    while i < 50:
        num = num + reverse_num(num)
        if is_palindrome(num):
            return False
        i += 1
    return True


count = 0
for x in xrange(1, 10000):
    if is_Lychrel(x):
        count += 1
print count

Question 56

A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 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, ab, where a, b < 100, what is the maximum digital sum? Show/Hide Solution

def sum_digits(num):
    my_sum = 0
    while num > 0:
        my_sum += (num%10)
        num /= 10
    return my_sum

max_sum = 0 
a = 1   
while a < 100:
    b = 1
    while b < 100:
        current_sum = sum_digits(a**b)
        print a, b, current_sum
        if max_sum < current_sum:
            max_sum = current_sum
        b += 1
    a += 1

print max_sum 

Question 92

A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before. For example, 44 → 32 → 13 → 10 → 1 → 1, and 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89. How many starting numbers below ten million will arrive at 89? Show/Hide Solution

import bisect

def create_new_num(num):
    str_list = list(str(num))
    my_sum = 0
    for each in str_list:
        my_sum += int(each)**2

    return my_sum

count = 0
i = 1
goes_to_89 = []
while i < 10000000:   
    x = i    
    looping = True
    new_nums = []
    while looping:
        x = create_new_num(x)
        if x in goes_to_89:
            count += 1
            looping = False
            break
        new_nums.append(x)
        if x == 1: 
            looping = False
        if x == 89:
            for each in new_nums:
                if each not in goes_to_89:
                    bisect.insort(goes_to_89, each)
            count += 1
            looping = False
    i += 1
            
answer = count
print answer