Highly Divisible Triangular Number — Project Euler (Problem 12)

All n numbers are Triangle Numbers. They’re called so, because they can be represented in the form of a triangular grid of points where the first row contains a single element and each subsequent row contains one more element than the previous one.

TriangularNumber_900

Problem 12 of Project Euler asks for the first triangle number with more than 500 divisors.

These are the factors of the first seven triangle numbers:

1 = 1: 1
2 = 3: 1,3
3 = 6: 1,2,3,6
4 = 10: 1,2,5,10
∑5 = 15: 1,3,5,15
∑6 = 21: 1,3,7,21
∑7 = 28: 1,2,4,7,14,28

Here’s how I proceeded:

First Step: Find the smallest number with 500 divisors. Seems like a good starting point to begin our search.
Second Step: Starting at the number found in the previous step, search for the next triangle number. Check to see whether this number has 500+ divisors. If yes, this is the number we were looking for, else…
Third Step: Check n for which ∑n = triangle number found in the previous step
Fourth Step: Add (n+1) to the last triangle number found, to find the next triangle number. Check whether this number has 500+ divisors. If yes, this number is the answer. If not, repeat Fourth Step till the process terminates.

Now for the details:

The First Step isn’t exactly a piece of cake, but necessary to reduce computation time. I solved this with a bit of mental math. The main tool for the feat is the prime number decomposition theorem:

Every integer N is the product of powers of prime numbers

N = pαqβ· … · rγ
Where p, q, …, r are prime, while α, β, …, γ are positive integers. Such representation is unique up to the order of the prime factors.
If N is a power of a prime, N = pα, then it has α + 1 factors:
1, p, …, pα-1, pα
The total number of factors of N equals (α + 1)(β + 1) … (γ + 1)

500 = 2 x 2 x 5 x 5 x 5
So, the number in question should be of the form abq4r4s4 where a, b, q, r, s are primes that minimize abq4r4s4. This is satisfied by 7x11x24x34x54 = 62370000. This marks the end of the First Step which is where we start our search for our magic number.

The next 3 steps would need helper functions defined as below:

from math import *
# Function to calculate the number of divisors of integer n
def divisors(n):
limit = int(sqrt(n))
divisors_list = []
for i in range(1, limit+1, 1):
if n % i == 0:
divisors_list.append(i)
if i != n/i:
divisors_list.append(n/i)
return len(divisors_list)
# Function to check for triangle number
def isTriangleNumber(n):
a = int(sqrt(2*n))
return 0.5*a*(a+1) == n
# Function to calculate the last term of the series adding up to the triangle number
def lastTerm(n):
if isTriangleNumber(n):
return int(sqrt(2*n))
else:
return None
view raw euler12functions.py hosted with ❤ by GitHub

As can be seen from the above code, the algorithm to calculate divisors of an integer is as follows:
1. Start by inputting a number n
2. Let an int variable limit = √n
3. Run a loop from i = 1 to  i = limit
    3.1 if n is divisible by i
3.1.1 Add i to the list of divisors
3.1.2 if i and n/i are unequal, add n/i to the list too.
4. End

Finally, executing the 4 steps mentioned earlier can be done like so (the code took less than 2s to arrive at the answer):

# First Step
# First number 'check' to have 500 divisors
check = 2**4 * 3**4 * 5**4 * 7 * 11
# Second Step
# Starting from 'check', iterate sequentially checking for the next 'triangle' number
while not isTriangleNumber(check):
check += 1
# Third and Fourth Steps
# Calculate the last term of the series ('seriesLastTerm') that adds up to the newly calculated triangle number 'check'
seriesLastTerm = lastTerm(check)
# Iterate over triangle numbers checking for divisors > 500
while divisors(check) <= 500:
# add the next term to check to get the next triangle number
check += (seriesLastTerm + 1)
seriesLastTerm += 1
print check

Ans: 76576500

Consecutive Prime Sum — Project Euler (Problem 50)

Many problems in Project Euler relate to working with primes. I use primesieve-python to help solve such problems. It consists of Python bindings for the primesieve C++ library. Generates primes orders of magnitude faster than any pure Python code. Features:

  • Generate a list of primes
  • Count primes and prime k-tuplets
  • Print primes and prime k-tuplets
  • Find the nth prime
  • Iterate over primes using little memory

Anyway, here’s Problem 50 from Project Euler:

ProjectEuler50

Here’s how I did it:

# Question: Which prime, below one-million, can be written as the sum of the most consecutive primes
from primesieve import *
from math import *
# Generate list of primes under a million
primes_under_million = generate_primes(10**6)
# Sum of consecutive primes is of order 0.5(n^2)(logn)
# Calculate 'n' so that sum of consecutive primes is less than a million (and not necessarily prime)
nsum = 1
n = 1
while nsum < 10**6:
nsum = 0.5*(n**2)*(log(n, e))
n += 1
# Calculate index so that sum of first 'index' consecutive primes is under a million and also prime
primes_subset = primes_under_million[:n]
nsum = sum(primes_under_million[:n])
while nsum > 10**6:
n -= 1
nsum = sum(primes_under_million[:n])
primes_sum = 0
index = 0
for i in range(len(primes_subset)):
if i % 2 == 1:
pass
else:
sumprimes = sum(primes_subset[:i])
if sumprimes > primes_sum and sumprimes < 10**6 and sumprimes in primes_under_million:
primes_sum = sumprimes
index = i
# Print out sum of consecutive primes till 'index', index, n
# print primes_sum, index, n
# Check consecutive primes within a range (index to n) such that their number is greater than index and maximum
j = index + 1
start = 0
while j <= n:
while (j-start) >= (n-index):
sumprimes = sum(primes_subset[start:j])
if sumprimes > primes_sum and sumprimes in primes_under_million:
primes_sum = sumprimes
start += 1
j += 1
start = 0
print primes_sum
view raw euler50.py hosted with ❤ by GitHub

Answer: 997651

Largest Product in a Grid — Project Euler (Problem 11)

I started solving Project Euler problems this month. Check out the Project Euler tab of this blog for a list of the problems I’ve solved (with solutions) till date. Here’s a problem you might find interesting:

ProjectEuler11

Here’s my solution using Python (I basically search through the entire matrix which is of O() complexity):

I first copy the maxtrix into a text file euler11.txt so that it can be later read into Python

08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
view raw euler11.txt hosted with ❤ by GitHub

I then execute the following code from the same working directory as euler11.txt
# import numpy module for matrix operations
from numpy import *
# read the file with the matrix of numbers
filename = 'euler11.txt'
# store each line of the file into an array
with open(filename, "r") as ins:
array = []
for line in ins:
array.append(line)
print array
# create a new array that converts the number strings into number integers
newArray = []
for i in array:
j = i.split(' ')
k = [int(n) for n in j]
newArray.append(k)
print newArray
# convert the array of integers into a matrix of integers
problemMatrix = matrix(newArray)
print problemMatrix
# set initial maximum product to be a dummy number, say 1
maxProd = 1
# search all combinations for maximum product
for i in range(16):
for j in range(16):
prod1 = problemMatrix[i,j]*problemMatrix[i+1,j]*problemMatrix[i+2,j]*problemMatrix[i+3,j]
if prod1 > maxProd:
maxProd = prod1
prod2 = problemMatrix[i,j]*problemMatrix[i,j+1]*problemMatrix[i,j+2]*problemMatrix[i,j+3]
if prod2 > maxProd:
maxProd = prod2
prod3 = problemMatrix[i,j]*problemMatrix[i+1,j+1]*problemMatrix[i+2,j+2]*problemMatrix[i+3,j+3]
if prod3 > maxProd:
maxProd = prod3
prod4 = problemMatrix[19-i,j]*problemMatrix[18-i,j+1]*problemMatrix[17-i,j+2]*problemMatrix[16-i,j+3]
if prod4 > maxProd:
maxProd = prod4
print maxProd
view raw euler11.py hosted with ❤ by GitHub

Answer: 70600674

Solution to [Viral] Math Puzzle for Vietnamese Eight-Year-Olds (Using R)

There was this math problem that went viral recently –  it was a Singapore Math Olympiad problem meant for 14-year olds which surprisingly many adults couldn’t solve. A friend sent me a link to that problem and I solved it with pen and paper in about 10 minutes, leaving me feeling hardly challenged. I guess really-tough questions aren’t the ones that actually go viral. If anything, a math problem going viral means it caters to an average IQ, something like a 100 – which then left me wondering whatever my IQ was! I had taken many online IQ tests when I was pursuing my engineering degree and my scores ranged between 135 and 145. But they weren’t tests one could really feel great about, mainly because everyone I knew who took them, scored 110+. I never took a Mensa test in the past, so I’m not sure whether I’d have made the cut. Anyway, I decided to check Quora to see if the nerds had found anything remotely mimicking a Mensa type IQ test. So I checked out this one and got a 130. It seems to be the least I’ve ever got on an IQ test, so without giving you any rationale to why I feel this might be closer to accurately measuring your IQ, I say it’s probably worth a shot.

iq_test_score

 

A week back, there was yet another math puzzle that had gone viral, meant for Vietnamese eight-year-olds, a problem that had stumped parents and teachers. You need to fill in the empty boxes below with the digits from 1 to 9 so that the equation makes sense, following the order of operations – multiply first, then division, addition and subtraction last. Apparently, this problem was for third graders in the town of Bao Loc in the Vietnamese Highlands.

I didn’t solve this one with pen and paper, and instead wrote an R program. It’s clearly a problem with a fixed number of variables (nine) associated with standard math operators, meaning there would be 9! (362880) permutations – which makes you think there’s got to be more than one solution. It became obvious I had to write some code.

I wrote a function appropriately named baoloc() to list out the solutions to this problem. The code is self explanatory. I got 128 unique solutions, which means if the students had to solve this problem with pencil on paper, they could get one of 128 possible answers, which makes the job of the examiner arduous and boring!

## The problem could be written as u + 13v/w + x + 12y - z - 11 + pq/r -10 = 66
## which reduces to u + 13v/w + x + 12y - z + pq/r = 87
## This problem was solved on [1] "Wed May 27 17:46:52 2015"
baoloc <- function()
{
packages <- rownames(installed.packages())
if("combinat" %in% packages) library("combinat") else install.packages("combinat")
numbers <- 1:9
permutations <- permn(numbers) ## list of all permutations of vector input
solutions <- numeric(9)
for(i in 1:length(permutations))
{
solution <- permutations[[i]]
if(solution[1] + 13*(solution[2]/solution[3]) + solution[4] + 12*solution[5] - solution[6] + (solution[7]*solution[8] / solution[9]) == 87)
{
solutions <- rbind(solutions, solution)
}
}
print("The number of solutions are:")
print(nrow(solutions)-1)
return(solutions[2:nrow(solutions),])
}
view raw baoloc.R hosted with ❤ by GitHub

The above code produces the following solutions:
[1] "The number of solutions are:"
[1] 128
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
solution 9 1 2 5 6 7 3 4 8
solution 7 9 6 1 5 2 3 4 8
solution 1 9 6 7 5 2 3 4 8
solution 1 5 2 3 4 8 7 9 6
solution 1 5 2 3 4 8 9 7 6
solution 5 1 2 9 6 7 3 4 8
solution 5 1 2 9 6 7 4 3 8
solution 1 5 2 8 4 7 3 9 6
solution 1 5 2 8 4 7 9 3 6
solution 1 9 6 7 5 2 4 3 8
solution 7 9 6 1 5 2 4 3 8
solution 9 1 2 5 6 7 4 3 8
solution 1 2 6 4 7 8 5 3 9
solution 1 2 6 4 7 8 3 5 9
solution 1 4 8 2 7 9 3 5 6
solution 1 4 8 2 7 9 5 3 6
solution 7 1 4 9 6 5 2 3 8
solution 9 1 4 7 6 5 2 3 8
solution 5 4 1 9 2 7 8 3 6
solution 5 4 1 9 2 7 3 8 6
solution 9 4 1 5 2 7 8 3 6
solution 9 4 1 5 2 7 3 8 6
solution 4 9 6 1 5 8 3 7 2
solution 4 9 6 1 5 8 7 3 2
solution 8 6 4 7 5 9 1 3 2
solution 7 6 4 8 5 9 1 3 2
solution 9 4 8 5 6 7 1 3 2
solution 5 4 8 9 6 7 1 3 2
solution 1 9 6 4 5 8 7 3 2
solution 1 9 6 4 5 8 3 7 2
solution 9 1 4 7 6 5 3 2 8
solution 7 1 4 9 6 5 3 2 8
solution 1 3 9 4 7 8 2 5 6
solution 1 3 4 7 6 5 2 9 8
solution 1 3 4 7 6 5 9 2 8
solution 1 3 9 4 7 8 5 2 6
solution 1 5 3 9 4 2 7 8 6
solution 1 5 3 9 4 2 8 7 6
solution 1 3 2 9 5 6 7 4 8
solution 1 3 2 9 5 6 4 7 8
solution 1 3 6 2 7 9 5 4 8
solution 1 3 6 2 7 9 4 5 8
solution 1 3 2 4 5 8 7 9 6
solution 1 3 2 4 5 8 9 7 6
solution 6 3 1 9 2 5 8 7 4
solution 6 3 1 9 2 5 7 8 4
solution 9 3 1 6 2 5 8 7 4
solution 9 3 1 6 2 5 7 8 4
solution 7 3 1 5 2 6 8 9 4
solution 7 3 1 5 2 6 9 8 4
solution 5 3 1 7 2 6 9 8 4
solution 5 3 1 7 2 6 8 9 4
solution 9 5 3 1 4 2 7 8 6
solution 9 5 3 1 4 2 8 7 6
solution 3 1 4 2 7 9 6 5 8
solution 3 1 4 2 7 9 5 6 8
solution 7 3 4 1 6 5 9 2 8
solution 7 3 4 1 6 5 2 9 8
solution 3 6 4 9 5 8 1 7 2
solution 3 6 4 9 5 8 7 1 2
solution 5 4 8 9 6 7 3 1 2
solution 9 4 8 5 6 7 3 1 2
solution 7 6 4 8 5 9 3 1 2
solution 8 6 4 7 5 9 3 1 2
solution 9 6 4 3 5 8 1 7 2
solution 9 6 4 3 5 8 7 1 2
solution 4 3 9 1 7 8 5 2 6
solution 4 3 9 1 7 8 2 5 6
solution 4 3 2 1 5 8 9 7 6
solution 4 3 2 1 5 8 7 9 6
solution 3 2 4 8 5 1 7 9 6
solution 3 2 4 8 5 1 9 7 6
solution 5 9 3 6 2 1 8 7 4
solution 5 9 3 6 2 1 7 8 4
solution 3 5 2 1 4 8 9 7 6
solution 3 5 2 1 4 8 7 9 6
solution 6 9 3 5 2 1 7 8 4
solution 6 9 3 5 2 1 8 7 4
solution 3 9 6 2 5 1 7 4 8
solution 3 9 6 2 5 1 4 7 8
solution 3 2 8 6 5 1 7 9 4
solution 3 2 8 6 5 1 9 7 4
solution 7 3 2 8 5 9 6 1 4
solution 8 3 2 7 5 9 6 1 4
solution 8 3 2 7 5 9 1 6 4
solution 7 3 2 8 5 9 1 6 4
solution 3 2 1 5 4 7 8 9 6
solution 3 2 1 5 4 7 9 8 6
solution 3 9 2 8 1 5 7 6 4
solution 9 3 2 1 5 6 7 4 8
solution 3 9 2 8 1 5 6 7 4
solution 9 3 2 1 5 6 4 7 8
solution 2 3 6 1 7 9 4 5 8
solution 2 3 6 1 7 9 5 4 8
solution 8 9 2 3 1 5 6 7 4
solution 8 9 2 3 1 5 7 6 4
solution 2 9 6 3 5 1 4 7 8
solution 2 9 6 3 5 1 7 4 8
solution 6 2 8 3 5 1 9 7 4
solution 6 2 8 3 5 1 7 9 4
solution 7 2 8 9 6 5 3 1 4
solution 9 2 8 7 6 5 3 1 4
solution 8 7 2 5 3 9 6 1 4
solution 8 7 2 5 3 9 1 6 4
solution 5 7 2 8 3 9 1 6 4
solution 5 7 2 8 3 9 6 1 4
solution 8 2 4 3 5 1 9 7 6
solution 8 2 4 3 5 1 7 9 6
solution 8 5 2 7 4 9 3 1 6
solution 7 5 2 8 4 9 3 1 6
solution 4 2 6 1 7 8 3 5 9
solution 4 2 6 1 7 8 5 3 9
solution 7 5 2 8 4 9 1 3 6
solution 8 5 2 7 4 9 1 3 6
solution 2 4 8 1 7 9 5 3 6
solution 2 8 6 9 4 1 5 7 3
solution 2 8 6 9 4 1 7 5 3
solution 9 8 6 2 4 1 7 5 3
solution 9 8 6 2 4 1 5 7 3
solution 2 4 8 1 7 9 3 5 6
solution 2 1 4 3 7 9 5 6 8
solution 2 1 4 3 7 9 6 5 8
solution 8 5 2 1 4 7 9 3 6
solution 8 5 2 1 4 7 3 9 6
solution 5 2 1 3 4 7 9 8 6
solution 5 2 1 3 4 7 8 9 6
solution 9 2 8 7 6 5 1 3 4
solution 7 2 8 9 6 5 1 3 4
view raw solution_baoloc.R hosted with ❤ by GitHub