Project Euler 7 - 9
Solving problems 7, 8, and 9 for Project Euler
In this post we will look at problems 7, 8, and 9 on Project Euler.
The same warning applies to this post as the first post in this series
Problem 7
Problem 7 gives us an example of the first 6 primes, and asks us to find the 10001st prime. We can easily find a way to count primes using a while loop, and verify that an incremented number is by writing a simple primality test.
In this example our isPrime()
function first eliminates 2 and then any even numbers, then use the any function to iterate over a range of 3 to the square root of our number plus 1, incremented by 2s, to get all odd numbers between 3 and the square root of a + 1. a % x == 0
checks to see if a is divisible by the numbers in the range, and if any are, returns True
, which is then negated by the not clause.
|
|
This gives us our example of 13, and if we modify the while loop to be 10001 instead of 6 we get the following solution:
Problem 8
Problem 9 gives us a 1000 digit number and tells us the greatest product of 4 adjacent digits is 5832 (9 x 9 x 8 x 9). Our task is to find the greatest product of 13 adjacent cells.
While this is technically a 1000 digit number, that does not necessarily mean we have to treat it as a number. In this case it would be easier to treat it as a string, and then iterate over our characters (digits) to find our adjacent numbers.
First we’ll set up a short function that will multiply the digits in a string together and return the product. Next we’ll have to create a variable with our 1000 digit number in it with a series of concatenations via the +=
operator. Next we’ll setup a for loop that will give us an index up to the end of the string, excluding the length of adjacent number of digits we are looking for (to prevent reading past the end of our string). We can then feed a slice of our string into our AdjProduct()
function and track the maximum result.
|
|
Running this gives us the example output of 5832, and if we update the adjNum
to 13 we get the following result:
Problem 9
Problem 9 gives us an example of a Pythagorean triplet below:
$$ a^2 + b^2 = c^2$$ $$\text{where: } a < b < c $$
We are then asked for the product of a * b * c where a + b + c = 1000.
We can start with a couple of nested for loops, one (b
) going to our limit, for the example we’ll use a sum of 15 to include the given numbers of 12, and a second for loop (a
) that limits at the previous to prevent a from being greater than b. We can then calculate c
using (a**2 + b**2)**.5
.
|
|
Running this gives us our example 60 (3 * 4 * 5), changing our limit to 1000 gives us the answer below:
Conclusion
That wraps up the third set of three problems from Project Euler. If you have any questions, please feel free to leave a comment below.