The post Project Euler 1 Solution appeared first on Dreamshire.

]]>Project Euler 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.

This is a typical application of the inclusion-exclusion principle. In general, sum the numbers less than 1000 that are divisible by 3 (3, 6, 9, 12, ** 15**, …)

This solution is much faster than using brute force which require loops, especially when the limit, `L`

, is large. Also note that we subtract 1 from the limit as the problem wants multiples __below__ `L`

.

Use this link to get the Project Euler 1 Solution Python 2.7 source.

- It’s helpful to know the formula for the sum of the first
*n*natural numbers (positive integers):

For example, when *n*=10 the sum of all the natural numbers from 1 through 10 is: (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10) = 10*11 / 2 = **55**.

Here’s how this formula works. Write the numbers in two rows that wrap around as shown below:

```
1 2 3 4 5
10 9 8 7 6
```

The sum of each column is 11 (i.e., *n*+1). As the top row increases, the bottom row decreases, so the column sum always stays the same and we’ll always have 2 rows and *n*/2 columns for any even number, *n*. If *n* is odd, start with zero instead of one.

which is the same formula as above.

We can adapt this formula to count the numbers only divisible by *d* to a specific limit; such as *n*=33, *d*=3, in the following example. Remember when there is an odd number we start from zero to keep the columns paired. Here’s how the adaptation works:

```
0 3 6 9 12 15
33 30 27 24 21 18
```

Each column sums to 33 and, using our understanding from above, we calculate 6*33 to find the sum of numbers to 33 that are evenly divisible by 3 (6*33=198). In the Python function `sumn`

this is accomplished by taking the floor of *n* divided by *d* to find the number of terms, then, modifying our formula to account for *d* (3, in this example), we calculate a sum.

The formula is the legacy of Carl Friedrich Gauss, the German mathematician. An anecdote of its discovery is retold below:

The sequence of numbers [1, 3, 6, 10, 15,…] are called the triangular numbers. The tenth number on the list is the number of beans required to build a triangle with ten rows, starting with one bean in the first row and ending with ten beans in the last row. The game of bowling or ten-pin sets 10 pins in a triangular form and thus uses the fourth number in this sequence.

To calculate the Nth triangular number you add the first N numbers: 1 + 2 + 3 + … + N. If you want to find the 100th triangular number, you begin the long and laborious addition of the first 100 numbers.

Indeed, Gauss’s teacher liked to assign these kinds of problems to his class as it would keep them busy and quiet for some time. As each student finished the task they would place their slate tablets with their answer written on it in a pile in front of the teacher. While the other students began laboring away, the ten-year-old Gauss had laid his tablet on the table within seconds. Dubious, the teacher thought the young Gauss was being lazy. But when he looked at Gauss’s slate, there was the answer — 5,050 — with no steps in the calculation. The teacher thought that Gauss must have cheated somehow, but the pupil explained that all you needed to do was put N=100 into the formula 1/2 × (N + 1) × N and you will get the 100th number in the list without having to calculate any other numbers on the list.

Rather than tackling the problem head on, Gauss had thought laterally. He argued that the best way to discover how many beans there were in a triangle with 100 rows was to take a second similar triangle of beans which could be placed upside down on top of the first triangle. Now Gauss had a rectangle with 101 rows each containing 100 beans. Calculating the number of beans in this rectangle built from the two triangles was easy: there are in total 101 × 100 = 10,100 beans. So one triangle must contain half this number, namely 1/2 × 101 × 100 = 5,050.

```
Example for 5 rows
``````
x o x o o o o o
x x o o x x o o o o
x x x o o o —> x x x o o o
x x x x o o o o x x x x o o
x x x x x o o o o o x x x x x o
```

Project Euler 1

The post Project Euler 1 Solution appeared first on Dreamshire.

]]>The post Project Euler 2 Solution appeared first on Dreamshire.

]]>Project Euler 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, …

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

The Fibonacci sequence is: 1, 1, * 2*, 3, 5,

To solve, sum every third number of the sequence that’s less than 4 million.

Example for L<400: The first even Fibonacci number to exceed 400 is 610. That terminates the loop and we are left with x=144 and y=610. 610+144 = 754, 754-2 = 752, and finally 752/4 = 188; the sum of all even Fibonacci numbers less than 400 (2+8+34+144 = 188).

Use this link to get the Project Euler 2 Solution Python 2.7 source.

|4613732|

- Good explaination on Fibonacci multiples: Fibonacci mod k, by Robert McCann, Univ. of Toronto Bahen Centre
- Reference: The On-Line Encyclopedia of Integer Sequences (OEIS) A000045: Fibonacci numbers: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.
- For a limit of 4,000,000 the loop iterates 11 times.
- The approximate ratio between two consecutive terms in the Fibonacci sequence is the golden ratio (phi, or φ ≈ 1.618034).

Phi is calculated as

The Fibonacci Series and the Golden Spiral

A Golden spiral is very similar to the Fibonacci spiral but is based on a series of identically proportioned golden rectangles, each having a golden ratio of 1.618 of the length of the long side to that of the short side of the rectangle:

The Fibonacci spiral gets closer and closer to a Golden Spiral as it increases in size because of the ratio of each number in the Fibonacci series to the one before it converges on Phi, 1.618, as the series progresses (e.g., 1, 1, 2, 3, 5, 8 and 13 produce ratios of 1, 2, 1.5, 1.67, 1.6 and 1.625, respectively)

The post Project Euler 2 Solution appeared first on Dreamshire.

]]>The post Project Euler 3 Solution appeared first on Dreamshire.

]]>Project Euler 3: The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

This can be done without the use of arrays or a giant list of prime numbers. Instead, we generate prospective prime numbers, *p*, as odd numbers, except for the first one which is 2.

The list of candidates for p are [2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, …]

As you can see many of these are not primes, but that’s OK, because their preceding factors have effectively eliminated them from consideration. For example, 9, 15, 21, … are removed when we divided by 3.

The last prime factor found is the largest and since every composite number has no prime factor greater than its square root we only need to check up to √*n*.

If the given number, *n*, is already prime then *n* is returned as the largest prime factor, which is nice, because it is, in fact, itself the largest prime factor.

Use this link to get the Project Euler 3 Solution Python 2.7 source.

|6857|

- Trial division, used here, works well for smaller numbers less than 10
^{21}, for larger numbers there are several efficient algorithms available. A more favorable method for factoring numbers under 100 digits long is the Quadratic sieve, a recent invention. It is a much simpler algorithm to implement compared to others and lends itself to parallelization. Because it is a sieve, large amounts of memory may be required.

Another is Pollard's Rho algorithm with improvements by Brent. It’s easy to program and fast for numbers with small factors.

To find the prime factors of any number see: prime factor calculator written in JavaScript.

- Some other examples:
*n*= 600851475143, iterations:738*n*= 600851475143600851475143, iterations:5006, largest prime:99990001, <1 sec*n*= 600856008514751431475143, iterations:11859442, largest prime:562585074706409, <6 sec

The post Project Euler 3 Solution appeared first on Dreamshire.

]]>The post Project Euler 4 Solution appeared first on Dreamshire.

]]>Project Euler 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.

A brutish way to find the largest palindrome product of two 3-digit numbers is by searching odd factors downwards from 999. We test each product as a palindrome and save it. Our search ends when the next product falls below the largest palindrome found and is less than our limit, *L*.

Nanogyth’s comment below demonstrates how to speed thing up significantly. It summarizes that if a six digit number is palindromic it must follow the form:

Where a, b, and c are integers such that 0 < a ≤ 9, 0 ≤ b, c ≤ 9

This means that one of our target factors has to be divisible by 11 and allows us to step our search index, `j`

, by 11 when `i`

is divisible by 11. When `i`

is not divisible by 11 we have to increment `j`

by 1.

This method could be easily extended for other even and odd length products for larger investigations.

The two factors are printed along with their product. *L* was added to solve the HackerRank version of Project Euler 4.

Use this link to get the Project Euler 4 Solution Python 2.7 source.

|906609|

- Function
`is_palindromic`

is listed in Common Functions and Routines for Project Euler - There are only 279 discrete 6-digit palindromes which are products of two 3-digit numbers.
- The largest palindrome for some other cases (Note: I restricted the search range to something sane):

# Digits | factor 1 | factor 2 | product | iterations |
---|---|---|---|---|

4 | 9999 | 9901 | 99000099 | 650 |

5 | 99979 | 99681 | 9966006699 | 55,655 |

6 | 999999 | 999001 | 999000000999 | 62,750 |

7 | 9997647 | 9998017 | 99956644665999 | 34,554,539 |

8 | 99999999 | 99990001 | 9999000000009999 | 6,252,500 |

9 | 999920317 | 999980347 | 999900665566009999 | – |

10 | 9999986701 | 9999996699 | 99999834000043899999 | – |

11 | 99999943851 | 99999996349 | 9999994020000204999999 | – |

12 | 999999000001 | 999999999999 | 999999000000000000999999 | – |

13 | 9999996340851 | 9999999993349 | 99999963342000024336999999 | – |

You can see that this method is quickly becoming impractical for a larger number of digits.

The post Project Euler 4 Solution appeared first on Dreamshire.

]]>The post Project Euler 5 Solution appeared first on Dreamshire.

]]>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 number that is evenly divisible by all of the numbers from 1 to 20?

The smallest positive number that is evenly divided (divided without remainder) by a set of numbers is called the Least Common Multiple (LCM). All we have to do is find the LCM for the integers {1, 2, 3, 4, …, 20} using Euclid’s algorithm.

After some reflection you might realize correctly that every integer is divisible by 1, so 1 can be removed from the list and calculate 2 through 20.

But by furthering this reasoning and we can eliminate other factors. We leave 20 in the calculation but then remove its factors {2, 4, 5, 10}. Any number evenly divisible by 20 is also evenly divisible by these factors. 19 is prime and has no factors – it stays. 18 has factors {2, 3, 6, 9} and we already removed 2 but we can remove 3, 6, and 9. 17 is prime – it stays too.

We continue this numeric carnage until our original list of {1..20} becomes the much smaller {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}. Following this reasoning, the lower half of the set is completely irrelevant and can be eliminated from consideration without changing the result.

```
from fractions import gcd
def lcm(a, b):
return a // gcd(a, b) * b
L = 20
print 'LCM of all numbers from 1 through', L, 'is', reduce(lcm, range(L//2+1, L+1))
```

For larger ranges, say greater than 10^{5}, this method becomes very slow. The method outlined below can adeptly handle larger sets such as {2, 3, 4, …, 10^{6}}.

Taking 20 as our example, we know the LCM must be divisible by every prime less than or equal to 20. In this case those primes are {2, 3, 5, 7, 11, 13, 17, 19}. For the primes less than square root of 20 there may be an exponent involved, and for those greater than the square root of 20 the exponent will always be 1. Let’s look at the breakdown:

Number | Prime Factors |
---|---|

11 | 11 |

12 | 2^{2}×3 |

13 | 13 |

14 | 2×7 |

15 | 2×5 |

16 | 2^{4} |

17 | 17 |

18 | 2×3^{2} |

19 | 19 |

20 | 2^{2}×5 |

Now, using the greatest exponent of each prime, multiply them together as:

2^{4} × 3^{2} × 5 × 7 × 11 × 13 × 17 × 19 = 232,792,560.

We use the log function to determine the exponent of the prime,*p*, as log(20)/log(p) by looping through the primes.

2

We use the log function to determine the exponent of the prime,

For example int(log(20)/log(2)) = 4; the largest exponent of 2 in the series (2^{4}=16). Again, int(log(20)/log(3)) = 2; the largest exponent of 3 in the series (2×3^{2}=18).

Use this link to get the Project Euler 5 Solution Python 2.7 source.

|232792560|

**Notes on Python usage:**

The statement:`from Euler import prime_sieve`

includes a function for calculating prime numbers from our Euler.py library module into the program. Many useful functions can be imported this way without copying its definition into each program. When an improvement is made or an error corrected it only has to be done once and is reflected in the scripts that import it. This keeps scripts short and concise. Function`prime_sieve`

is listed in Common Functions and Routines for Project Euler.In the GCD version we changed

`return a * b / gcd(a,b)`

to`return a / gcd(a,b) * b`

. “Because gcd(a, b) is a divisor of both a and b, it’s more efficient to compute the LCM by dividing before multiplying. This reduces the size of one input for both the division and the multiplication, and reduces the required storage needed for intermediate results (overflow in the a×b computation).” [from Wikipedia]Python’s

`reduce`

(*function*,*sequence*,*initial value*) returns a single value constructed by calling the binary function`mul`

on the first two items of the sequence, then on the result and the next item and so on.- The code shown below removes the use of reduce to achieve the same results.

```
a = 1
for p in primes:
a*= p**int(log(L)/log(p))
```

The post Project Euler 5 Solution appeared first on Dreamshire.

]]>The post Project Euler 6 Solution appeared first on Dreamshire.

]]>Project Euler 6: The sum of the squares of the first ten natural numbers is,

1² + 2² + … + 10² = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + … + 10)² = 55² = 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.

Solving this problem requires the knowledge of two established formulas:

1. The sum of the first *n* numbers (triangular numbers, used in Problem 1):

2. The sum of the first *n* square numbers (square pyramidal numbers):

We apply these formulas to our range [1,*n*] and find the difference. These formulas will come in useful for solving other problems.

Now, I guess for the purists one could perform the subtraction of these two summations and derive the following formula:

Avoiding loops to solve these types of problems in favor of formulas and closed-form calculations becomes apparent when you are asked to solve 10,000 problems with much higher limits in a fixed amount of time, typically less than a few seconds.

This program and method

solves all test cases

on HackerRank

solves all test cases

on HackerRank

Use this link to get the Project Euler 6 Solution Python 2.7 source.

|25164150|

- Reference: The On-Line Encyclopedia of Integer Sequences (OEIS) A000330: Square pyramidal numbers: a(n) = 0^2 + 1^2 + 2^2 + ... + n^2 = n*(n+1)*(2*n+1)/6.

1, 5, 14, 30, 55, 91, 140, 204, 285, 385, 506, 650, 819, … - For a visual example of pyramidal numbers, imagine stacking cannon balls

The post Project Euler 6 Solution appeared first on Dreamshire.

]]>The post Project Euler 7 Solution appeared first on Dreamshire.

]]>By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6^{th} prime is 13.

What is the 10001^{st} prime number?

I wanted a solution that would solve both this problem and the HackerRank.com version of Project Euler 7 which queries hundreds of *n*th prime numbers. So, the quickest and easiest way is simply to generate enough primes as a list and use it’s index (or ordinal position – 10001 in this example) to find the answer. The prime generator featured here is fast and can generate 20 million primes in less than one-half second.

Since our prime sieve function generates prime numbers below some limit, it’s prudent to make this limit as close to our biggest *n*th prime as possible to conserve resources. The inverse of the Prime Counting Function generates a good guess. This function takes a number, *n*, and calculates the number of primes below it, so the inverse takes a number of primes and tells us how high our limit must be to include them.

There is a handy calculator here and a table here if you want to learn more about the prime counting function, π(x), and how to determine a reasonable limit.

This program and method

solves all test cases

on HackerRank

solves all test cases

on HackerRank

Use this link to get the Project Euler 7 Solution Python 2.7 source.

|104743|

- Function
`prime_sieve`

is listed in Common Functions and Routines for Project Euler - If this problem were to ask for the 100,001st prime number, then using the calculator mentioned above, we would need to generate all primes less than 1,300,000 to make sure it was included. The answer would be 1,299,721.
- Calculating prime numbers is a recurring theme throughout Project Euler so you may want to add this function to your library to help solve other problems.

The post Project Euler 7 Solution appeared first on Dreamshire.

]]>The post Project Euler 8 Solution appeared first on Dreamshire.

]]>Find the greatest product of 13 consecutive digits for a large number.

73167176531330624919225119674426574742355349194934

96983520312774506326239578318016984801869478851843

… {continued}

Convert the strings to a list of single digits and find the maximum product taking into consideration all 13-digit contiguous groups. You could map zeros as their group’s product would be zero, or search the space for groups with large factors (e.g., nines and eights) if you were so inclined. But, hey, this same algorithm solved the much more aggressive HackerRank version just fine.

80% of the Python solutions listed in the Project Euler forum are wrong as they don’t consider the last digit in the search space. Because the solution to this problem lies in the middle of the search space, these programs calculate a correct response. If you were to run them with the following parameters they would fail by erroneously produce zero as an answer instead of 18:

d = [0,0,0,1,9,2]

L = 3

Further, many of these programs would return an error or zero(a distinct possibility) which could be misleading; it’s better to return some indication that an answer cannot be calculated, such as “None,” to indicate that a maximum product could not be found for 13 digits:

d = [0,0,0,1,9,2]

L = 13

This program and method

solves all test cases

on HackerRank

solves all test cases

on HackerRank

Use this link to get the Project Euler 8 Solution Python 2.7 source.

|23514624000|

- PEP 8 is the style guide for Python. It describes the preferred methods for formatting Python source code for a consistent appearance. We do our best to follow those guidelines to make the code as readable as possible.

But sometimes lines of Python can get a bit confusing, such as:

`d = map(int, ''.join(line.rstrip() for line in open('pe8.txt')))`

and may need further explanation:

The above line opens and reads the file “pe8.txt” (the second tab next to the main.py tab in the Trinket window) and concatenates each line into one long string by stripping (rstrip) the new line character (\n) from the end of the lines. Finally, each character is separated and converted to an integer before being added to a list named * d*.

The post Project Euler 8 Solution appeared first on Dreamshire.

]]>The post Project Euler 9 Solution appeared first on Dreamshire.

]]>A Pythagorean triplet is a set of three natural numbers, `a` ≤ `b` < `c`, for which,

For example,

.

There exists exactly one Pythagorean triplet for which `a` + `b` + `c` = 1000.

Find the product `abc`.

A Pythagorean triple consists of three positive integers *a*, *b*, and *c*, such that *a*^{2} + *b*^{2} = *c*^{2}. These triples are commonly written as (*a*, *b*, *c*), and a typical example is (3, 4, 5); 3^{2} + 4^{2} = 5^{2} or 9 + 16 = 25.

A primitive Pythagorean triple is one in which *a*, *b* and *c* are coprime (gcd(*a*, *b*, *c*) = 1) and for any primitive Pythagorean triple, (*ka*, *kb*, *kc*) for any positive integer *k* is a non-primitive Pythagorean triple.

Solving this problem for one target sum: *a* + *b* + *c* = 1000 in this case, seemed a bit too trivial but solving for any target sum ≤ 3000 and running thousands of trials in a few milliseconds was a bit more challenging.

This solution uses Dickson’s method for generating Pythagorean triples.

To find integer solutions to *a*^{2} + *b*^{2} = *c*^{2}, find positive integers *r*, *s*, and *t* such that is a square.

Then: *a* = *r* + *s*, *b* = *r* + *t*, *c* = *r* + *s* + *t*.

From this we see that *r* is any even integer and that *s* and *t* are factors of

Example: Choose r = 6. Then .

The three factor-pairs of 18 are: (1, 18), (2, 9), and (3, 6). All three factor pairs will produce triples using the above equations.

s = 1, t = 18 produces the triple [7, 24, 25] because x = 6 + 1 = **7**, y = 6 + 18 = **24**, z = 6 + 1 + 18 = **25**.

s = 2, t = 9 produces the triple [8, 15, 17] because x = 6 + 2 =**8**, y = 6 + 9 = **15**, z = 6 + 2 + 9 = **17**.

s = 3, t = 6 produces the triple [9, 12, 15] because x = 6 + 3 =**9**, y = 6 + 6 = **12**, z = 6 + 3 + 6 = **15**. (Since s and t are not coprime, this triple is not primitive.)

s = 2, t = 9 produces the triple [8, 15, 17] because x = 6 + 2 =

s = 3, t = 6 produces the triple [9, 12, 15] because x = 6 + 3 =

This method finds both primitive (when *s* and *t* are coprime) and non-primitive triplets, which are required to solve this problem.

We loop through the even *r* up to 550 to generate all the triplets necessary to solve different problems. In the case of triples having the same sum this method keeps the maximum product found.

For example, Pythagorean triples (15, 20, 25) and (10, 24, 26) both sum to 60, but their respective products are 7500 and 6240. We keep the maximum, 7500.

This program and method

solves all test cases

on HackerRank

solves all test cases

on HackerRank

Use this link to get the Project Euler 9 Solution Python 2.7 source.

|31875000|

- This code was written to handle thousands of queries on a single run and is why we cache the results of triplet sums from 2 to 3000 in the
`pn`

dictionary. - Generating Pythagorean Triples

The post Project Euler 9 Solution appeared first on Dreamshire.

]]>