The post Project Euler 49 Solution appeared first on Dreamshire.
]]>The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.
What 12-digit number do you form by concatenating the three terms in this sequence?
Start with the known solution plus 2 (1489) and find the next set checking only odd numbers.
is_prime, is_perm
are listed in Common Functions and Routines for Project Euler
The post Project Euler 49 Solution appeared first on Dreamshire.
]]>The post Project Euler 46 Solution appeared first on Dreamshire.
]]>Project Euler 46: It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 2×1^{2}
15 = 7 + 2×2^{2}
21 = 3 + 2×3^{2}
25 = 7 + 2×3^{2}
27 = 19 + 2×2^{2}
33 = 31 + 2×1^{2}
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square
I love how Chris was tossing a bunch of stuff out there and then letting someone else prove him wrong, if, in fact, it really was wrong. His famous conjecture (every even integer greater than 2 can be expressed as the sum of two primes) has stood the test of time even today, but some doubt it may hold forever. Gotta love the guy.
I give it a try: pi is an irrational number, then it’s fractional part is infinite and represents every numerical sequence possible. This would include a series of 14s repeated an infinite number of times or s many time that enumerating them as fast as the smallest discreet division of time would outlast time itself. The same goes for 09876. And any infinite other number of endings. So, you see, it does repeat and you can claim any series you like. You’re welcome.
Sorry for the fill here, just needed a bit more content for this post since there’s not much to be said for explaining the solution.
Sieve primes as we go along (because we have no idea how many it’s going to take) using our knowledge from Problem 7 and check the proposal until a odd composite is found.
The post Project Euler 46 Solution appeared first on Dreamshire.
]]>The post Project Euler 40 Solution appeared first on Dreamshire.
]]>Project Euler 40: An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021…
It can be seen that the 12^{th} digit of the fractional part is 1.
If d_{n} represents the n^{th} digit of the fractional part, find the value of the following expression.
d_{1} × d_{10} × d_{100} × d_{1000} × d_{10000} × d_{100000} × d_{1000000}
A simple solution is to create a string one million digits long by concatenating the counting numbers starting from 1 to 185,185 (known as Champernowne's constant). Then multiply together the single digits at the positions specified in the problem statememt. We know from the problem description that the first two terms d_{1} & d_{10} will evaluate to 1 and, therefore, have no effect on the product. Here’s my early perl implementation of this brute force method:
$s = '.'; $n = 1; $s.= $n++ while(length($s) <= 1_000_000); print "Answer to PE40 = ", substr($s,100,1)*substr($s,1e3,1)*substr($s,1e4,1)*substr($s,1e5,1)*substr($s,1e6,1);
Of course this will not handle the more assailing parameters of the HackerRank Project Euler 40 version with 7 positions in a 10^{18} digit number run with 100,000 consecutive trials. A better approach must be devised.
You can think of Champernowne's constant, hereinafter known simply as "constant," as a concatenation of many series of concatenated counting numbers. Each series represents an order of magnitude or, more succinctly, a power of 10 as follows:
Series (k) | Range | Number of terms | Number of characters in series | Number of characters total |
---|---|---|---|---|
1 | 1-9 | 9 | 9 | 9 |
2 | 10-99 | 90 | 180 | 189 |
3 | 100-999 | 900 | 2700 | 2889 |
4 | 1000-9999 | 9000 | 36000 | 38889 |
5 | 10000-99999 | 90000 | 450000 | 488889 |
We can make a few observations:
We can reimagine this series of concatenated numbers as an array with 3 indexes. One for the series, one for the term in the series, and one for the decimal position inside the term. All of these indexes will be derived from a single index that describes the digit inside the constant. This is made possible by the organized construction of the constant.
Let's say we want the 27th digit inside the constant. We would decode 27 into the 3 indexes as follows:
Series 1: 1,2,3,4,5,6,7,8,9
Series 2: 10,11,12,13,14,15,16,17,18,19,20,21,22,…,99
The 27th digit in the constant is 8.
Let's take the 37371st digit in the constant as an example. We need first to find the series the digit resides:
#bc is the character length of each series: 9, 180, 2700, ..., 9·x·10^(x-1) sc = [pow(10, x-1) * 9*x for x in xrange(1, 50)] n = 37371 i = 0 while n>sc[i]: n-= sc[i]; i+= 1
At the end of this loop we find our digit, 37371, is in the 4th series which follows our understanding: 9+180+2700 < 37371 ≤ 9+180+2700+36000. Since all the terms in the 4th series are 4-digits we take the residual value of n, the 34482nd term in the constant or (34482-1)/4 = 8620 (remainder 1) in the series. The index is (34482-1) because our series starts with an index base of 0.
We add the starting range, 1,000, for series 4 and 9620 is the term's value. Since the remainder is 1, and we base our substring selection starting from 0, we take the second digit of this number for our answer.
The 37371st digit in the constant is 6.
Times @@ Flatten[IntegerDigits@Range@2*^5][[10^Range@6]]
The post Project Euler 40 Solution appeared first on Dreamshire.
]]>The post Project Euler 24 Solution appeared first on Dreamshire.
]]>Project Euler 24: A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
Our algorithm recursively calculates the permutations of ever decreasing subsets keeping the sets in lexicographical order. By convention, these permutations count from zero, so we subtract 1 from the target (1,000,000).
itertools
versionfrom itertools import permutations as perm print ''.join(list(perm('0123456789',10))[999999])
Let’s investigate an example, step-by-step, to get an idea of how we can determine our permutation one element at a time.
An example for [A B C D]
The complete lexicographic order for 4 symbols: A, B, C, D Total permutations = 4! or 3!x4 = 24 Col 0 Col 1 Col 2 Col 3 00 [A B C D] 06 [B A C D] 12 [C A B D] 18 [D A B C] 01 [A B D C] 07 [B A D C] 13 [C A D B] 19 [D A C B] 02 [A C B D] 08 [B C A D] 14 [C B A D] 20 [D B A C] 03 [A C D B] 09 [B C D A] 15 [C B D A] 21 [D B C A] 04 [A D B C] 10 [B D A C] 16 [C D A B] 22 [D C A B] 05 [A D C B] 11 [B D C A] 17 [C D B A] 23 [D C B A]
Let’s find the 10th lexicographic permutation (index 9 starting from zero or the 10th entry). The data is arranged in a rectangular grid 3! rows by 4 columns, i.e. 6×4.
If we just want the first number for the 10th arrangement we can see it’s in column 1, which makes sense because the first 3! arrangements will start with ‘A’ the second 3! with ‘B’ and so on. So, to calculate the column we simply integer divide our desired index, 9, by 3! which equals 1.
The column and the first element of our 10th lexicographic permutation:
9/3! = 1 with 3 remainder. That is, column 1 which all start with ‘B’. ‘B‘ is the first element.
Now let’s create a new table without ‘B’ since it has now been placed in the first position:
The complete lexicographic order for 3 symbols: A, C, D Total permutations = 3! or 2!x3 = 6 Col 0 Col 1 Col 2 00 [A C D] 02 [C A D] 04 [D A C] 01 [A D C] 03 [C D A] 05 [D C A]
Remember our remainder of 3 from the previous calculation? Well, that’s now our new index for the next element.
3/2! = 1 with 1 remainder. That is, column 1 which all start with ‘C’. ‘C‘ is the second element.
Let’s do this one last time:
The complete lexicographic order for 2 symbols: A, D Total permutations = 2! or 1!x2 = 2 Col 0 Col 1 00 [A D] 01 [D A]
Again, recall our remainder of 1 from the previous calculation.
1/1 = 1 with 0 remainder. That’s column 1 or ‘D‘ and the last dependent position will be filled by ‘A‘. Our 10th lexicographic permutation is [B C D A].
Now, using this algorithm, lets get the first 4 digits to the millionth lexicographic permutation of the digits [0 1 2 3 4 5 6 7 8 9].
[0 1 2 3 4 5 6 7 8 9]
First digit: 999999/9! = 2 with 274239 remainder. First digit is at index 2 (starting from 0) or ‘2‘
2 [0 1 3 4 5 6 7 8 9]
Second digit: 274239/8! = 6 with 32319 remainder. Second digit is at index 6 or ‘7‘
2 7 [0 1 3 4 5 6 8 9]
Third digit: 32319/7! = 6 with 2079 remainder. Third digit is at index 6 or ‘8‘
2 7 8 [0 1 3 4 5 6 9]
Fourth digit: 2079/6! = 2 with 639 remainder. Fourth digit is at index 2 or ‘3‘
2 7 8 3 [0 1 4 5 6 9]
This method lends itself to recurrence nicely by building the result one element at a time. It will recursively call itself each time reducing the size of the set by 1 by removing the placed element from the previous iteration.
Even though HackerRank steps up the challenge by increasing the set to 13 characters and proving 1000 trials and 10 test cases, this algorithm still solves them in one-hundredth of a second.
perm
is listed in Common Functions and Routines for Project EulerProject Euler 24
The post Project Euler 24 Solution appeared first on Dreamshire.
]]>The post Project Euler 27 Solution appeared first on Dreamshire.
]]>Project Euler 27: Euler published the remarkable quadratic formula:
n² + n + 41
It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 40^{2} + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² + 41 + 41 is clearly divisible by 41.
Using computers, the incredible formula n² − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479.
Considering quadratics of the form:
n² + an + b, where |a| < 1000 and |b| < 1000, where |n| is the modulus/absolute value of n
e.g. |11| = 11 and |−4| = 4
Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0.
Note: The quadratic formula needs only to generate prime numbers, not necessarily unique nor consecutive prime numbers.
This problem is wanting us to find two coefficients, a and b, to a quadratic expression, n² + an + b, that will generate the most prime numbers when evaluated with n starting from zero and incremented by one until a non-prime is evaluated. The coefficients a and b are constrained as -1000 < a < 1000 and -1000 < b < 1000.
Using simple iteration of a and b over their range will produce a result for this specific problem, but take too long for the more complex inquiry from HackerRank.
The are a few observations that will help improve performance.
The problem requires our n to start at 0, and since we are looking for prime numbers with consecutive values of n, our first result from a quadratic equation would be 0^{2} – 0 + b which evaluates simply to b. So b has to be positive, prime and less than 1000 (for this problem) which helps reduce the search space significantly.
Additionally, we can now start n
at 1 since we know the first outcome is guaranteed prime. Our sieve, prime_sieve(L)
, generates primes less than L
. Adding 1 to our limit, guarantees L
gets included should it be a prime number.
Prime number 2 is excluded from the possible starting primes as it evaluates to an even number after 1 or 2 iterations.
If you further consider when n=1, then the expression becomes 1-a+b or 1+a+b, which must always evaluate to an odd number to yield a possible prime. We know b+1 will be even so a must be odd. We can now infer that a must be odd and |a| < b which supports our thinking.
HackerRank Project Euler 27 adds the constraint that the coefficients a and b in the range [-2000,-42] U [42,2000]. The positive constraint on a and b can be ignored as we previously established; effectively halving the search range. We are asked to print the two coefficients a and b instead of the product of a and b.
prime_sieve, is_prime
are listed in Common Functions and Routines for Project Euler. They are also included in the “Euler.py” Trinket tab next to the “main.py” tab.The post Project Euler 27 Solution appeared first on Dreamshire.
]]>The post Project Euler 12 Solution appeared first on Dreamshire.
]]>Project Euler 12: The sequence of triangle numbers is generated by adding the natural numbers. So the 7^{th} triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …
Let us list the factors of the first seven triangle numbers:
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
This problem sounds simple enough, but it is somewhat dastardly in getting results both quicky and correctly. The premise is to query triangular numbers (recall problem 1) and find the first one to have more than 500 divisors.
Our algorithm for solving this one was markedly improved by a detailed explanation provided by a Project Euler moderator named ‘rayfil’. Yet it still wasn’t fast enough to handle the more challenging hackerRank Project Euler 12 version with finding a triangle number with 1,000 divisors and 10 consecutive trials.
To solve, we sieve the number of divisors as we check each candidate for being a triangular number. The result was being able to solve for 5000 divisors in less than 10 seconds. Now, one may question the somewhat arbitrary value for n=4200
. It’s a cap on the potential triangular number index search used to tune the algorithm for performance. It could be set to some other high value to accommodate deeper investigations.
The post Project Euler 12 Solution appeared first on Dreamshire.
]]>The post Project Euler 14 Solution appeared first on Dreamshire.
]]>Project Euler 14: The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
The Python program listed in the Afterthoughts section shows the hailstone
calculator for determining values in the Collatz chain for a number, N. The d
function determines the length of the chain and the purpose of the program is to determine the longest length for a set of consecutive numbers below some limit, L
. It became apparent that the lengths were simply a collection of discrete points over the domain.
So, when challenged by HackerRank Project Euler 14 with more aggressive limits (N<=10,000,000), and running thousands of trials in fewer than 5 seconds it became obvious that building a table was the best way to go.
There are fragments of this sequence in the OEIS but a problem was the requirement to find the maximum starting value when the same chain length is shared by other starting numbers.
For example 35497 is not found in these on-line sequences and for an N=34555 the starting number for the longest chain returned is 34239. Well it seems the 35497 shares the same number of terms and is the greater of the two. 35497 is the correct response.
This required going backwards through a range of numbers (say 10^{7}) and finding the stopping points and taking these maximums into consideration. That result is the list shown in the Python source code below.
L = 1000000
hailstone = lambda n: 3*n + 1 if n%2 else n//2
def d(n, _={1:1}):
if n not in _: _[n] = d(hailstone(n)) + 1
return _[n]
print max(range(1, L), key=d)
The post Project Euler 14 Solution appeared first on Dreamshire.
]]>The post Project Euler 20 Solution appeared first on Dreamshire.
]]>Project Euler 20: n! means n × (n − 1) × … × 3 × 2 × 1
Find the sum of the digits in the number 100!
This problem can be solved using the same method as used for problem 16 to sum the digits of a very large integer. (See also, Project Euler 16 Solution: )
The solution comes down to one statement that encompasses several steps:
factorial()
)
str()
).
map()
),
sum()
).
sum(map(int, str(factorial(N))))
5. Print the result.
The print statement uses placeholders with formatting directives which are filled in with the results following the final ‘%’.
print "Sum of digits for %d! = %d" % ( N, sum(map(int, str(factorial(N)))) )
This program was designed to solve this problem for 100! and the HackerRank version for N! with N ≤ 1000, with up to 100 trials in less than a hundredth of a second.
You could improve things some if you ignore trailing zeros as they don’t contribute to the sum of the digits. The table below shows how the trailing zeros increase as the factorials become larger. Also, here’s a program that will calculate the number of trailing zeros in a factorial.
Factorial | # of digits | # trailing zeros | % of length |
---|---|---|---|
100! | 158 | 24 | 15% |
1000! | 2568 | 249 | 9% |
10000! | 35660 | 2499 | 14% |
factorial
function initiates a reduce
function to 1 and uses reduce to multiply successive integers from 2 through n to compute a factorial.
def factorial(n): return reduce(lambda x,y: x*y, xrange(2, n+1), 1)
The post Project Euler 20 Solution appeared first on Dreamshire.
]]>The post Project Euler 16 Solution appeared first on Dreamshire.
]]>Project Euler 16: 2^{15} = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^{1000}?
We are asked to calculate a very large power of 2 and sum the individual digits of the result. As Python natively supports arbitrary precision integers, with millions of digits if necessary, it makes this task easy to do.
We calculate 2^{1000} and convert the result to a string: sum(map(int, str(pow(2, 1000))))
. Next, using the map
function with the result string at the iterator and int
as the application function we split the digits of the result into individual characters and convert to integers: sum(map(int, str(pow(2, 1000))))
. The sum of the digits is calculated by the sum
function as the answer to the problem: sum(map(int, str(pow(2, 1000))))
.
The HackerRank Project Euler 16 version increases the exponent to 10,000 and runs a hundred trials in a few milliseconds. Same solution.
The post Project Euler 16 Solution appeared first on Dreamshire.
]]>The post Project Euler 13 Solution appeared first on Dreamshire.
]]>Project Euler 13: Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
This problem requires us to find the first 10 (leftmost) digits of the sum of one hundred 50-digit integers.
The numbers were saved to a file named pe13.txt (second Trinket tab next to the main.py tab). This keeps the data and the program separate and the process easy to comprehend.
The file is read as strings and converted to a list of integers using the map
function with open
as the iterator and int
as the application function: sum(map(int, open('pe13.txt')))
. After the end of the file is reached the list is fed to the sum
function which adds the integers together: sum(map(int, open('pe13.txt')))
. This integer sum is finally converted to a string str(total)[:10] and truncated to the top 10 digits for a solution: str(total)[:10].
HackerRank increases the data set from 100 to 1000 numbers. Same solution.
print "Top 10 digits of sum =", str(sum(map(int, open('pe13.txt'))))[:10]
Have a great day – and check out some of my other pages.
Thanks,
your friend,
Mike
June 8, 2014
The post Project Euler 13 Solution appeared first on Dreamshire.
]]>