Project Euler # 18

Project Euler # 18

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

7 4
4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)

Brute Force

The obvious solution is to brute force the solution by trying every possible route, through recursion. However, since at each junction the path branches into two, there will be 214 = 16384 routes. With a 100 rows, there will be 299 rows, which is way too much to brute force!

Non – Obvious method

Let us understand this with the help of this small triangle:

7 4
4 6
8 5 9 3

Each element can lead to the element directly below, or the element directly below and to the right.

Assuming a given element is a point on the solution path, the next element has to be the greatest of the two possible elements. Thus add the greatest number below a given number to it and iterate upwards. This is demonstrated on the small triangle.


7 4
4 6
8 5 9 3

Add bottom row elements to the top.

8 > 5

9 > 5

9 > 3

7 4
10 13 15
8 5 9 3

Add the new row to the row above it.

10 < 13

13 < 15

20 19
10 13 15
8 5 9 3

And again, add the new row, this time to the topmost row.

20  > 19

20 19
10 13 15
8 5 9 3

The topmost element is the largest sum!

Source in C++

Data file containing triangle (Program reads from this file)

Note: You can use this to solve problem 67 as well. Remember to change array sizes, iteration limits and the data file!


Project Euler – Problem 10

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Problem 10 is reasonably demanding. Unless you are familiar with Eratosthenes Sieve method (or any other sieve method), solving this problem in less than a minute will be next to impossible.

Sieve of Eratosthenes

In mathematics, the sieve of Eratosthenes , one of a number of prime number sieves, is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2.
Wikipedia Entry

General Algorithm

Above is a visual representation of the algorithm. Now, we must translate it into program code, in order to solve the problem.

  1. Declare an Boolean array with 2,000,000 elements (since we want to find primes less than 2 million).
  2. Fill the entire array with ‘true’ or 1. By doing this, we are assuming that all the numbers are prime. We will now “cross out” (mark false) those numbers which are multiples of other numbers.
  3. For each value of ifrom 2 to 2000000:
    1. Visit the ith element of the array. If it is true, then:
      1. For each element (j) which is a multiple of i, change the value of array[j]to false.
      2. Add the value of i to the sum.
    2. Else, continue iterating.
  4. Print the sum.

On my machine, the program takes about 0.063 seconds to run. It’s slightly memory intensive, requiring an array of 2000000 bytes to be allocated, but it can’t be helped.
If you know of some other prime number sieve which works faster, do let me know.

Solution in C++ 

Project Euler – Problem 9

Problem 9 is sort of easy too! 🙂

The problem statement is as follows:

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.

Knowing a little maths can take you a long way in this problem.

Mathematical Discussion

(skip this it bores you. The problem can still be solved without it)

Knowing this can cut your run time from 0.291 seconds to 0.001 seconds (as measured by the ctime library), which is basically 99.6% faster!

Basically, Pythagorean Triplets are an expression for possible integral values of the sides of a right angled triangle. Armed with this little nugget of knowledge, we can effectively reduce the iterations that we have to go through to find the required triplet.

General Algorithm

  1. We know that a + b + c = 1000.
  2. Therefore, m2 n2 + 2mn + m2 + n2 = 1000. So, 2m2 + 2mn = 1000.
  3. We now attempt to get the answer by applying brute force on the above expression, rather than plugging in all possible values of a, b and c.
  4. I believe that the brute force method merits no discussion. It has been included in the source, for comparison with the above method.

Solution in C++ 

Project Euler – Problem 8

Problem 8 of Project Euler gets a little tricky! In order to save yourself some time, you must know a little bit of file input and output in whatever language you program in.
While the number is small enough to be attacked by brute force, it can be a pain to hand-code it into an array. Copy-paste the number into a text file or download it from here.


The problem, as stated on the website:

Find the greatest product of five consecutive digits in the 1000-digit number.


General Algorithm

  1. To solve this problem, we read each digit from the file, and push it onto vector <int> number. This is done till we reach the end of the file.
  2.  Once we have the number in our vector/array, we iterate through it, 5 digits at a time, and find the product. At the end we display the maximum product.

Solution in C++

Note: Syntax for File I/O varies differs based on language.

Project Euler – Problem 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?

Problem 7 is pretty easy too!

General Algorithm

  1. Begin testing numbers to see if they are prime, starting from 2.
  2. Break the loop when you have found 10001 prime numbers.

It’s that simple. 102,892 people have solved this problem.

Run time: 0.062 s.  Do let me know if you manage to make an improvement.

Solution in C++

Project Euler – Problem 6

Problem 6 is by far one of the easiest problems yet.

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.

Again, there are at – least two possible methods. One is our dear friend, Mr. Brute Force 🙂 The other is more mathematical.

Brute force description

There’s not much to be said about this one. Create loops to add the sum of numbers from 1 to 100, and another loop to add the squares of numbers from 1 to 100. Square the sum you get in the first loop, and then find it’s difference. It’s simple.

Mathematical Approach

To understand the mathematical approach, you must have knowledge of the two formulas given below:

It’s all high school maths. They are easy to prove as well, especially the first one.
Writing out functions for the above should not be a difficult task, whatever language you choose.

In my version, I’ve written them as Macros (using the # pre processor directive)


For a single iteration, both methods take less than 0.001 s or 1 ms which means they can’t be measured. Over 1,000,000 iterations, the brute force method takes 0.723 s while the other approach still clocks in at a nifty 0.001 s.

Solution in C++

Project Euler – Problem 5

Problem 5, from the Project Euler website:

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?

This problem can easily be solved by using brute force, in about 3.61 seconds. While that’s not blazing, it’s under the one – minute time limit.

A more logical approach gives the answer in 0.02 seconds. I will take up both methods and discuss them.

General Algorithm I

This is the brute force method. It involves continuous iteration untill a number is found which is divisible by all the numbers from 1 to 20.

  1. Declare i = 1;
  2. Repeat the following steps:
    1. Divide i by all the numbers from 1 to 20.
    2. If it is not perfectly divisible by any of the numbers, increment i and continue.
    3. If it is perfectly divisible then i is the number we are looking for. Print i and break the loop.

This method gives a run-time of about 8 seconds. One slight modification can be made:
Instead of dividing from 1 to 20, it is sufficient to check from 11 to 20, because all the number within this range are multiples of the preceding numbers.

Making the above modifications cuts down the run-time to the mentioned 3.61 seconds. 

General Algorithm II

A little elementary maths go into this approach:

The smallest number which is exactly divisible by a set of numbers, is the LCM (Least Common Multiple) of those numbers.

So the number that we’re looking for is the LCM of the numbers 1 through 20.

  1. int Answer = 1.
  2. Iterate i from 1 to 20.
  3. Answer is now the LCM of i and Answer.
  4. At the end of the loop, the value of Answer is the required number.

Finding the LCM of two numbers:

  1. A and B are the two integers whose LCM must be found.
  2. Initialize LCM as 1.
  3. If both A and B  are divisible by any integer from 2 to A, divide both A and B by that integer and multiply the LCM by it. Also, begin checking for common factors from 2.
  4. After no more divisions are possible, multiply LCM by A and B.
  5. This is the LCM of A and B.

Another approach to LCM:

HCF(a,b) * LCM(a,b) = a * b

Figure out an algorithm for the HCF of two numbers by yourself! 🙂

Solution in C++

Project Euler – Problem 4

The problem description, from the Project Euler website:

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.

Again, a little brute force never hurt anybody 😛

General Algorithm

Before you begin, you must identify how exactly your going to check if a number is a palindrome. The question defines a palindrome for you: A palindromic number reads the same both ways. IMO, the easiest way to check if a number is a palindrome is to reverse it and see if it is equal to it’s original value. Given below is a general reverse algorithm.

  1. Initialize reversed number to zero.
  2. While the number to be reversed (n), is not zero:
    1. Get the last digit by n % 10.
    2. Make it a subsequent digit of the reversed number by doing the following:
      1. Reversed number  *= 10.
      2. Reversed Number += last digit.
    3. Remove the last digit (n /= 10).
  3. At the end of the loop, you will have the reversed number.

I guess the iteration for checking the product of every 3 digit number needs no explanation.

Solution in C++

Note: If you’re having trouble with _int64 on your compiler, replace it with long long int

Project Euler – Problem 3

Problem 3 of Project Euler is a computational beast. Nothing more. The problem, as stated on the website is:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

General Algorithm

Before we start, we have to take a few things into account:

  1. 600851475143 is an insanely large number. Languages like C/C++ have no native support for big integers. Luckily for us, we can store this in a long long unsigned int.
  2. While testing for primes, the following information must be kept in mind:
  3. While the definition of prime numbers is known to most, the second point is rather important. It implies that we need only to check for factors of a number till √n and not till n.

The algorithm is as follows:

  1. Initialise const long long unsigned int n = 600851475143.
  2.  Iterate i through every integer from √n to 1.
  3. If i perfectly divides n, then:
    • If i is prime then the highest factor is i
    • If i is not prime, then check if n/i is prime. If n/i  is prime, then n/i is the highest factor.
    • If neither i nor n/i  is prime, then continue through the loop
  1. Break the loop.

Solution in C++ 

Project Euler – Problem 2

The Problem:

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.

General Algorithm:

Again, a fairly iterative problem. It explains what the Fibonacci sequence is. In terms of mathematical operations, it is defined as:


The process is continuous. So continue to repeat this, to get successive terms.

  1. Initialize a sum variable to 0.
  2. Iterate through all the term of the Fibonacci sequence.
  3. If a term is more than 4,000,000 then break the loop
  4. Otherwise add it to the sum.
  5. When the loop breaks, print the sum.

Solution in C++