The post Project Euler 51 Solution appeared first on Dreamshire.
]]>Project Euler 51: By replacing the 1^{st} digit of *57, it turns out that six of the possible values: 157, 257, 457, 557, 757, and 857, are all prime.
By replacing the 3^{rd} and 4^{th} digits of 56**3 with the same digit, this 5digit number is the first example having seven primes, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.
Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.
REVISED
We induced that for an eight prime value family we were looking for a 6digit prime number with 3 repeated digits. You can’t have 2 or 4 repeating digits because at least one of the 8 versions will be divisible by 3. There are only 68,906 6digit prime numbers to consider, but with some thought we could eliminate most of them. Here’s the process we used:
1. We need look at only those primes that have exactly 3 repeating digits.
2. The last (least significant) digit can’t be the repeating digit, because replacing it would allow composite numbers (Thanks, Rabino.)
3. Lastly, since we are checking for an eight prime value family, we need only those primes that have their repeating digit 0, 1 or 2; this reduced the set to only 1,305 primes.
Now we can iterate through the primes and report the first one that had eight prime versions.
The post Project Euler 51 Solution appeared first on Dreamshire.
]]>The post Project Euler 52 Solution appeared first on Dreamshire.
]]>It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
This is a rehash of an old high school problem on repeating digits:
1/7 = 0.142857 142857 142857 ...
2/7 = 0.285714 285714 285714 ...
3/7 = 0.428571 428571 428571 ...
4/7 = 0.571428 571428 571428 ...
5/7 = 0.714285 714285 714285 ...
6/7 = 0.857142 857142 857142 ...
I’m sure you get the idea without giving away the answer.
As for our programmatic solution: an assumption that the digits didn’t have to be unique, I set the number of digits less one as our starting bound and search sequentially by sorting the digits within each number and comparing for multiples 1, 2, 3, 4, 5 and 6.
We can begin our search with a 5 digit multiple of 9, such as 99999, because the result has at least 6 digits. Also, because any number and its permutation always differ by a multiple of 9 (ex., (4512111542)/9 = 3731) we can increment by 9 instead of 1.
The post Project Euler 52 Solution appeared first on Dreamshire.
]]>The post Project Euler 53 Solution appeared first on Dreamshire.
]]>Project Euler 53: There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, ^{5}C_{3} = 10.
In general, ^{n}C_{r} = n! / r!(n−r)!, where r ≤ n, n! = n×(n−1)×…×3×2×1, and 0! = 1.
It is not until n = 23, that a value exceeds onemillion: ^{23}C_{10} = 1144066.
How many, not necessarily distinct, values of ^{n}C_{r}, for 1 ≤ n ≤ 100, are greater than onemillion?
There is an efficient way to solve this using Pascal’s triangle.
1  
1  1  
1  2  1  
1  3  3  1  
1  4  6  4  1  
1  5  10  10  5  1  
1  6  15  20  15  6  1  
1  7  21  35  35  21  7  1 
Each row of this triangle is vertically symmetric, so C(n, r) = C(n, nr) and any C(n, x) for x from r to (nr) is greater than C(n, r).
If C(n, r) > 10^{6} then C(n, x) for x from r to (nr) will also > 10^{6}, therefore, the number of C(n, r) > 10^{6}, is simply (nr)r+1 for that row n.
binomial
is listed in Common Functions and Routines for Project EulerThe post Project Euler 53 Solution appeared first on Dreamshire.
]]>The post Project Euler 54 Solution appeared first on Dreamshire.
]]>Project Euler 54: In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:
The cards are valued in the order:
2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.
If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on.
Consider the following five hands dealt to two players:
Hand  Player 1  Player 2  Winner  
1  5H 5C 6S 7S KD
Pair of Fives

2C 3S 8S 8D TD
Pair of Eights

Player 2  
2  5D 8C 9S JS AC
Highest card Ace

2C 5C 7D 8S QH
Highest card Queen

Player 1  
3  2D 9C AS AH AC
Three Aces

3D 6D 7D TD QD
Flush with Diamonds

Player 2  
4  4D 6S 9H QH QC
Pair of Queens
Highest card Nine 
3D 6D 7H QD QS
Pair of Queens
Highest card Seven 
Player 1  
5  2H 2D 4C 4D 4S
Full House
With Three Fours 
3C 3D 3S 9S 9D
Full House
with Three Threes 
Player 1 
The file, poker.txt, contains onethousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1’s cards and the last five are Player 2’s cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player’s hand is in no specific order, and in each hand there is a clear winner.
How many hands does Player 1 win?
If we can quantify each hand into an array of tuples we can quickly compare each hand and determine a winner or a tie.
The first tuple would consist between 2 and 5 elements representing the frequency of card values sorted in descending order. The second tuple would consist of the same number of elements as the first but describe the value sorted and weighted by frequency in descending order.
Let’s check out how this would look for a few typical hands for both players:
p1 = TH 6H 9H QH JH [(1, 1, 1, 1, 1), (12, 11, 10, 9, 6)], score = 0
p2 = 9H 4D JC KS JS [(2, 1, 1, 1), (11, 13, 9, 4)], score = 1
p1 = 7C 7S KC KS JC [(2, 2, 1), (13, 7, 11)], score = 2
p2 = 7H 7D KH KD 9S [(2, 2, 1), (13, 7, 9)], score = 2
Ties in similar scores are broken by checking the second tuple
By simply comparing hands as p1>p2 we can determine the winner between the two players. The only complication left is to calculate and rank straights and flushes.
The post Project Euler 54 Solution appeared first on Dreamshire.
]]>The post Project Euler 55 Solution appeared first on Dreamshire.
]]>Project Euler 55: If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below tenthousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28digits).
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.
How many Lychrel numbers are there below tenthousand?
NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers.
“Lychrel” is pronounced La’shrell and rhymes with bell. These number are for amusement and serve little practicable purpose. Being said, however, it is a curiosity that deserves to be explored if for no better reason than to develop an algorithm to disprove their existence. 196Algorithm is the official name given to programs that investigate Lychrel numbers, and to date, brute force testing has not proven that Lychrel numbers don’t exist as is the case with 196 – the algorithm’s namesake.
Our bounds are specified by the problem’s description; specifically to search a range from 10 to 9999 and only check a depth to 49 iterations.
The function is_lychrel() takes the candidate and adds itself to its reverse. If this sum is a palindrome then it’s not a Lychrel number and we return a false (zero) result. This process is repeated up to 49 (depth) times and returns true (one) only if it passes all iterations without producing a palindrome. This does not confirm with irrefutability the number to be a Lychrel number as deeper iterations could disprove the number’s Lychrel status. However, for 196, billions of iterations have yet to force its abdication from the throne of possible Lychrel numbers.
is_palindromic
is listed in Common Functions and Routines for Project EulerThe post Project Euler 55 Solution appeared first on Dreamshire.
]]>The post Project Euler 56 Solution appeared first on Dreamshire.
]]>Project Euler 56: A googol (10^{100}) is a massive number: one followed by onehundred zeros; 100^{100} is almost unimaginably large: one followed by twohundred zeros. Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, a^{b}, where a, b < 100,
what is the maximum digital sum?
This is an easy problem to solve with Python, much like Project Euler 16, because of the language’s native large integer support and adept string handling.
The HackerRank limits are not that more aggressive as it only extends the limit from 100 to 200. And the same solution presented below easily solves both challenges:
print max(sum(map(int, str(a**b))) for a in xrange(100) for b in xrange(100))
In order to improve performance, with the only intention to see how much processing time could be saved, new starting limits for the base and exponent were discovered.
Selecting a new starting range was based on one assumption: the more digits, greater than the average digit value 4, the bigger the sum. This assumption focuses attention on looking at the larger exponents. So, smaller powers in the search range can be skipped and we can reduce the base (a
) to start at 60% of the limit and the exponent (b
) at 80% of the limit. We proved empirically that both of these reductions satisfy any query with an a
and b
less than 1000. In fact, the reduction factors for the base and exponent can increase to 85% and 90%, respectively, with larger values of a
and b
.
The python expression below will separate each digit from the calculated power and add them together. This is accomplished by converting the numerical power (a**b
) to a string, which is iterable, and using the map
function to convert each character (digit) into an integer. These integers are then summed into a digital sum.
sum(map(int, str(a**b)))
As each power is calculated and the sum of their digits evaluated they are buffered into a collection, like an array, where the maximum of the collection is selected.
The post Project Euler 56 Solution appeared first on Dreamshire.
]]>The post Project Euler 57 Solution appeared first on Dreamshire.
]]>Project Euler 57: It is possible to show that the square root of two can be expressed as an infinite continued fraction.
√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + … ))) = 1.414213…
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666…
1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379…
The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.
In the first onethousand expansions, how many fractions contain a numerator with more digits than denominator?
The early Pythagoreans were convinced that every conceivable number could in principle be written in fractional form, as the ratio of two natural numbers. Since there is an infinite supply of these numbers, they reasoned, there must be enough to do the job. The discovery that this was an mistaken belief, possibly by the Pythagorean philosopher Hippasus in the 5th century BCE, was shocking news. According to legend, Hippasus was hurled off a boat and drowned to prevent the truth becoming widely known, such was its threat to the Pythagorean concept of order in the Universe.
Expand the series as 2d + n for the numerator and d+n for the denominator and count the number of times the length of the numerator exceeds the denominator as strings.
Using base 10 logs for the number of digits comparison between the numerator and denominator yields a 100 times speed improvement over comparing the lengths of them converted to strings.
Also, at this time the Trinket version below is not calculating logs correctly. Until they fix it you can switch to a string comparison as:
if len(str(n)) > len(str(d)): c += 1
x
are the points where the numerator exceeds the denominator.The post Project Euler 57 Solution appeared first on Dreamshire.
]]>The post Project Euler 58 Solution appeared first on Dreamshire.
]]>Starting with 1 and spiralling counterclockwise in the following way, a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.
If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?
Forget about the geometry and determine the series instead: (3, 5, 7, 9), (13, 17, 21, 25), (31, 37, 43, 49), … This represents the “corners” for every square layer.
Determine and count the primes, p_{n}, in the series ignoring every 4th one since it will always be a square and therefore composite. As soon as we reach a ratio of primes to series length (n), p_{n}/n < 10% we can calculate a side length as n/2.
It’s important to have a decent is_prime() function to achieve a better run time.
miller_rabin
is listed in Common Functions and Routines for Project Eulermiller_rabin
, in place of is_prime
sped things up 3 fold. We are using the default accuracy of 5 which is low but fast.The post Project Euler 58 Solution appeared first on Dreamshire.
]]>The post Project Euler 59 Solution appeared first on Dreamshire.
]]>Project Euler 59: Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message.
Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable.
Your task has been made easy, as the encryption key consists of three lower case characters. Using cipher1.txt (right click and ‘Save Link/Target As…’), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text.
The encoded message is read as a list of ASCII values from a local file (second Trinket tab, p059_cipher.txt). The decryption process is simplified by limiting the key to three characters from the set {a..z} for only 17,576 possibilities.
Taking the suggestion from the comment below, we look for the space character.
We have to repeat each key cyclically until it’s the same length as the message. For example, if the message is “gduii9iu” and the password is ‘abc’ we must decrypt with ‘abcabcab’.
The post Project Euler 59 Solution appeared first on Dreamshire.
]]>The post Project Euler 60 Solution appeared first on Dreamshire.
]]>The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.
Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
Our idea was to use set intersection to quickly find an answer. The problem was that “quick” was not a word to describe this solution. It sounded good, but doesn’t scale well from the parameters described in the problem. Here’s the methodology:
Find pairs of concatenable primes and then use each set to find intersections with other sets. So, for 3 the other primes less than 1,000 that are concatenable are:
3 [7, 11, 17, 31, 37, 59, 67, 73, 109, 137, 191, 229, 271, 331, 359, 373, 449, 467, 499, 541, 557, 607, 613, 617, 673, 701, 719, 733, 739, 823, 929, 947]
So, we need to search each of these sets starting with 7:
7 [19, 61, 97, 109, 127, 229, 283, 433, 487, 523, 541, 547, 673, 691, 757, 823, 829, 853, 883, 937]
The intersection of these sets is:
{109, 229, 541, 673, 823}
Check the above set for 2 primes that can concatenate to make other primes and a 4 prime set is found {3, 7, 109, 673}
Ok, that might work, but I shifted gears and just recursively built a list of primes, two at a time, that could be concatenated. Then took that pair and built a threeprime set. Keep this line of thinking going and after 30 seconds it found the fiveprime set.
I randomly selected 10,000 as a prime upper limit thinking it would need to be bigger, but after seeing the results only 8400 would have been sufficient.
The post Project Euler 60 Solution appeared first on Dreamshire.
]]>