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 problem wants us to find the sum of all the natural numbers (positive integers) below 1000 that are evenly divided by 3, such as 3, 6, 9, … and 5, such as 5, 10, 15, …

This can be implemented quickly and intuitively by using an iterative approach that loops through a range of integers between 1 and 999. Using the mod operator to check for even divisibility (a 0 remainder after division) we sum those integers, `i`

, that are divisible by 3 or 5.

# single line using list comprehensions in python print sum(i for i in xrange(1, 1000) if i%3==0 or i%5==0) # a classical way in python s = 0 for i in xrange(1, 1000): if i%3==0 or i%5==0: s+= i print s

The program runs instantly for the less than 1000 limit but we quickly learn that this method does not scale to larger ranges such as 1 billion run 100,000 times is less than a second. Such is the demand required to be met by the HackerRank Project Euler 1. So we need to find a more efficient way of calculating this sum without looping.

There is a formula, attributed to Carl Friedrich Gauss, that will calculate the sum of the first *n* natural numbers and, by extension, the first *nth* natural numbers where *nth* will be 3 and 5 respectively.

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 calculate the sum using the expanded formula below which accounts for the multiplier *d*.

By applying the above formula to *n*=999 and *d*=3 and *d*=5 we get the sums for every 3rd and 5th number. Adding those together is almost our answer but we must first subtract the sum of every 15th natural number (3 × 5) as it is counted twice: once in the 3 summation and once again in the 5 summation.

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.

- This understanding is used again to help solve Project Euler Problem 6.
- Legacy:

The formula is the legacy of Carl Friedrich Gauss, the German mathematician. Here’s how he figured it out:

The sequence of numbers [1, 3, 6, 10, 15,…] are called the triangular numbers. The game of bowling or ten-pin sets 10 pins in a triangular form and thus uses the fourth number in this sequence. One pin in the first row and ending with 4 pins in the last row.

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 further additions.

Rather than tackling the problem head on, Gauss had thought geometrically. 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 problem is asking to consider all Fibonacci numbers less than or equal to 4 million and sum the even numbered ones.

The sequence is formally defined by the recurrence relation:

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

This is because adding two odd numbers (1+1) sum to an even number, followed by adding 2 sets of even and odd numbers (1+2 and 2+3) which sum to an odd number. This principle propagates through the series *ad infinitum*. A good explaination on Fibonacci multiples, such as the even ones, is provided in the paper: Fibonacci mod k, by Robert McCann, Univ. of Toronto Bahen Centre.

To solve, we will need a program for this limit of 4×10^{6} and the hackerRank Project Euler 2 version which requires us to test 100,000 problems at once with a more ambitious limit of 4×10^{16} in less than a second. We can bypass iterating the full sequence and just focus on every third term.

This can be easily achieved by defining a new generalized Fibonacci sequence of even Fibonacci numbers starting from zero as: {0, 2, 8, 34, 144, 610, … }.

This works very well, requiring only 11 iterations for a limit of 4×10^{6} and 27 iterations for 4×10^{16}.

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

- Generalized Fibonacci sequences are used again in Project Euler Problem 104
- 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.
- 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)

Project Euler 2

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 ?

The question asks that if the the number 600851475143 was factored into its distinct prime factors, report the largest one found.

This can be done without the use of arrays or a giant list of prime numbers. Instead, we generate prospective prime numbers, `p`

, through sieving. The list of candidates for `p`

are the set of odd natural numbers {2, 3, 5, 7, 9, 11, 13, 15, …}.

The remainder, after removing all other prime factors, `p`

, is the largest prime factor and we can terminate the loop when the current candidate’s square exceeds the residual value of `n`

.

p = 2 while (p*p <= n): if (n % p == 0): n //= p else: p += 2 if p>2 else 1 # after 2, consider only odd p Here's a trace of this algorithm to demonstrate the process of removing prime factors from the numbernand leaving the largest prime factorp. n=495pp^{2}np=2 and 4 ≤ 495: 2 is not a factor so its skipped and p is incremented to 3 p=3 and 9 ≤ 495: 3 is a factor: n = 165 p=3 and 9 ≤ 165: 3 is a factor: n = 55 p=3 and 9 ≤ 55: 3 is not a factor so its skipped and p is incremented to 5 p=5 and 25 ≤ 55: 5 is a factor: n = 11 p=5 and 25 ≤ 55: 5 is not a factor so its skipped and p is incremented to 7 p=7 and 49 ≤ 55: 7 is not a factor so its skipped and p is incremented to 9 p=9 and 81 not ≤ 55: p is incremented to 11 and the`while`

loop terminates.The conditional of the`while`

loop is checked after the loop's last statement.

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. Here’s a Javascript prime factor calculator to find all the prime factors of a number.

The HackerRank version ups the limit for *n*≤10^{12} and runs test cases up to 10 consecutive trials. This algorithm handles those test cases in less than a tenth of a second.

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

- 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 factor: 99990001, <1 sec*n*= 600856008514751431475143, iterations:11859442, largest prime factor: 562585074706409, <6 sec

Project Euler 3

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.

We are tasked with finding the largest palindromic number with two 3 digit factors. One method is searching factors downwards from 999 as it is more likely to find a larger product from larger factors. We test each product as a palindrome and save it and continue until we exhaust all our potential factors.

Nanogyth’s comment below demonstrates how to speed things 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 decrement `j`

by 1.

Here’s my initial simple brute-force solution; about 0.3 seconds, but not fast enough for bigger problems.

print max(i*j for i in xrange(1000) for j in xrange(i,1000) if str(i*j)==str(i*j)[::-1])

The final solution is presented below and simply performs an exhaustive investigation of 3-digit factors starting from the biggest factors until a maximum palindrome product is found. There’s an early out condition that breaks the inside loop (`j`

) by finding a palindrome less than the current maximum. This is allowed because palindrome products are found in descending order from the perspective of the inside loop.

One subtle optimization was to check the limit before checking if the product is a palindrome as the palindrome check is more computationally expensive. If the first condition is false the succeeding conditions are ignored.

if p < L and is_palindromic(p): x, y, pmax = i, j, p

The two factors are printed along with their product. *L* was added to solve the HackerRank Project Euler 4 version which keeps the search to 3 digit factors but includes a limit to the palindrome product.

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

- 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 |
---|---|---|---|

4 | 9999 | 9901 | 99000099 |

5 | 99979 | 99681 | 9966006699 |

6 | 999999 | 999001 | 999000000999 |

7 | 9997647 | 9998017 | 99956644665999 |

8 | 99999999 | 99990001 | 9999000000009999 |

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 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.

]]>Project Euler 5: 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 | Number | Prime Factors |
---|---|---|---|

11 | 11 | 16 | 2^{4} |

12 | 2^{2}×3
| 17 | 17 |

13 | 13 | 18 | 2×3^{2} |

14 | 2×7 | 19 | 19 |

15 | 2×5 | 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, the floor of (log 20 / log 2) = 4; the largest exponent of **2** in the prime factors (2^{4} = 16). Again, the floor of (log 20 / log 3) = 2; the largest exponent of **3** in the prime factors (2×3^{2}=18).

The HackerRank version ups the limit for 1 ≤ n ≤ 40 and runs up to 10 consecutive test cases. This algorithm handles those test cases in less than a hundredth of a second.

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

**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))
```

Project Euler 5

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 Project Euler Problem 1):

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

For a visual example of square pyramidal numbers, imagine stacking cannon balls:

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 with the more demanding hackerRank Project Euler 6 version. It requires you to solve up to 10,000 trials with a higher limit of n ≤ 10,000 in a fixed amount of time, typically less than a tenth of a second.

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

- 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, … }.

The post Project Euler 6 Solution appeared first on Dreamshire.

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

]]>Project Euler 7: 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 to simply generate enough primes into a list and use it’s index (or ordinal position) to find the answer. The prime generator featured here is fast and can generate 20 million primes in less than one-half second.

The extra list element, `[0]`

, prepended to the `prime`

list is to allow the *nth* prime to be the *nth* element without having to worry about the list starting from 0.

from Euler import prime_sieve print prime_sieve(105000)[10000] #10000 and not 10001 because the list is zero-based#105000 so we have at least 10001 prime numbers

Since our prime sieve function generates prime numbers below some numerical 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. The calculator reports that there are 10,024 primes less than 105,000 which covers both this problem and the HackerRank version.

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

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

- Function
`prime_sieve`

is listed in Common Functions and Routines for Project Euler. The function is also included here in the second Trinket tab named “Euler.py” next to the “main.py” tab. - 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 (which calculates 100,021 primes) to make sure it was included. The 100,001st prime is 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.

]]>Project Euler 8: Find the greatest product of 13 consecutive digits for a large number.

The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.

73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 ... {continued}

Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

All the lines of numbers are to be considered as one, very long, 1000-digit number and are presented this way for readability. The objective is to canvass this number and find the greatest product of 13 contiguous digits.

We begin by opening and reading the file “pe8.txt” (the second tab next to the main.py tab in the Trinket window) and concatenate each line into one long string by stripping (`rstrip`

method) whitespace (which includes the new line character, \n) from the end of the lines. Next, each character is separated, converted to an integer digit, and added to a list named `d`

.

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

If you can be assured that a group product greater than zero exists, you could map individual zeros and move the search pointer forward. But, hey, this same algorithm solved the much more aggressive HackerRank version just fine.

A length (`L`

) is set defining the search length, 13 for this exercise, and we make sure there are enough digits to search. If not we exit printing “None.”

If there are enough digits, we consider each 13-digit set until the end, taking into account the search length: 1000-13+1 = 988. The `reduce`

function runs each set through a multiplier and we capture the maximum product of all sets.

L = 13 print 'Greatest product of', L, 'consecutive \ndigits =', print "None." if L>len(d) else \ max(reduce(mul, d[i:i+L]) for i in xrange(len(d)-L+1))

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 somewhere, these programs calculate a correct response in this instance. If you were to run them with the following parameters they would fail by erroneously producing a zero instead of 18:

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

L = 3

Further, many of these same erroneous 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 an undefined condition:

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

L = 13

HackerRank Project Euler 8 steps up the complexity a bit by running up to 100 trials and changing the search length from a fixed 13 digits to a variable 1 through 7 digits. The search object can range from 1 to 1000 digits and will be at least the size of the search length.

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

- 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.

Project Euler 8

The post Project Euler 8 Solution appeared first on Dreamshire.

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

]]>Project Euler 9: 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 (that is, gcd(*a*, *b*, *c*) = 1; they have no common factors between them) and for any primitive Pythagorean triple a non-primitive Pythagorean triple can be calculated as: (*ka*, *kb*, *kc*) for any positive integer *k*.

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 *r*^{2} = 2*st* is a square; then: *a* = *r* + *s*, *b* = *r* + *t*, and *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 triplets (when *s* and *t* are coprime) and non-primitive triplets.

We loop through the even numbered *r* and add the sums to a dictionary. In the case of triples having the same sum this method keeps the maximum product found. 550 was used as a limit to solve all the possible queries for sums less than or equal to 3000. This will solve this problem and all the hackerRank problems.

pn = {} for r in range(2, 550, 2): st = r*r // 2 for s, t in divisors(st): x = (r+s) + (r+t) + (r+s+t) pn[x] = (r+s) * (r+t) * (r+s+t)

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 is achieved as a result of both using a dictionary and finding the products in ascending order.

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

- Pythagorean sums are always even.
- 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

Project Euler 9

The post Project Euler 9 Solution appeared first on Dreamshire.

]]>