The post Project Euler 100 Solution appeared first on Dreamshire.
]]>If a box contains twentyone coloured discs, composed of fifteen blue discs and six red discs, and two discs were taken at random, it can be seen that the probability of taking two blue discs, P(BB) = (15/21)×(14/20) = 1/2.
The next such arrangement, for which there is exactly 50% chance of taking two blue discs at random, is a box containing eightyfive blue discs and thirtyfive red discs.
By finding the first arrangement to contain over 10^{12} = 1,000,000,000,000 discs in total, determine the number of blue discs that the box would contain.
Given b=blue discs, n=total number of discs then the general equation is:
which is, in fact, a Diophantine Quadratic Equation and can be solved using a program provided on the following website: http://www.alpertron.com.ar/QUAD.HTM
Here is the input to the program for our equation:
[ 2] x^{2} +
[ 0] xy +
[1] y^{2} +
[2] x +
[ 1] y +
[ 0] = 0
Here is the output from the program:
2x^{2} – y^{2} – 2x + y = 0
X_{0} = 0
Y_{0} = 1
and also:
X_{0} = 1
Y_{0} = 1
X_{n+1} = 3X_{n} + 2Y_{n} – 2
Y_{n+1} = 4X_{n} + 3Y_{n} – 3
From here we have two equations that can calculate b and n for each term in the series. Instead of starting at b=1, n=1 we start with the values in the problem description to save a few iterations; b=85, n=120. We continue this series until n>10^{12}.
The equations are: blue disks = 3b + 2n – 2; n disks = 4b + 3n – 3 (also n = int(b/√2/2), but that’s another story).
The post Project Euler 100 Solution appeared first on Dreamshire.
]]>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.
from Euler import prime_sieve, is_prime
import string
def eight_prime_family(prime, rd):
c=0
for digit in '0123456789':
n = int(string.replace(prime, rd, digit))
if (n>100000 and is_prime(n)):
c=c+1
return c==8
for prime in prime_sieve(1000000):
if (prime>100000):
s = str(prime)
last_digit = s[5:6]
if (s.count('0')==3 and eight_prime_family(s,'0') \
or s.count('1')==3 and last_digit != '1' and eight_prime_family(s,'1') \
or s.count('2')==3 and eight_prime_family(s,'2')):
print "Project Euler 51 Solution: ",s
Use this link to get the Project Euler 51 Solution Python 2.7 source.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.
]]>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.
from collections import Counter
from urllib2 import urlopen
file_url = 'https://projecteuler.net/project/resources/p054_poker.txt'
hands = (line.split() for line in urlopen(file_url))
values = {r:i for i,r in enumerate('23456789TJQKA', start=2)}
straights = [(v, v1, v2, v3, v4) for v in range(14, 5, 1)] + [(14, 5, 4, 3, 2)]
ranks = [(1,1,1,1,1),(2,1,1,1),(2,2,1),(3,1,1),(),(),(3,2),(4,1)]
def hand_rank(hand):
score = zip(*sorted(((v, values[k]) for
k,v in Counter(x[0] for x in hand).items()), reverse=True))
score[0] = ranks.index(score[0])
if len(set(card[1] for card in hand)) == 1: score[0] = 5 # flush
if score[1] in straights: score[0] = 8 if score[0] == 5 else 4 # str./str. flush
return score
print "Project Euler 54 Solution =", sum(hand_rank(hand[:5]) > hand_rank(hand[5:]) for hand in hands)
Use this link to get the Project Euler 54 Solution Python 2.7 source.The post Project Euler 54 Solution appeared first on Dreamshire.
]]>The post Project Euler 55 Solution appeared first on Dreamshire.
]]>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.
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 zero (false) result. This process is repeated up to 49 (depth) times and returns one (true) only if it passes all iterations.
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 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.
from Euler import miller_rabin as m_r
n_prime, d, avg, n = 0, 1, 1, 2
while avg >= 0.10:
n_prime += m_r(d + n) + m_r(d + n*2) + m_r(d + n*3)
d += n*4
n += 2
avg = n_prime / (2.0 * n) # the decimal forces a float calculation
print "Project Euler 58 Solution =", n1
Use this link to get the Project Euler 58 Solution Python 2.7 source.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.
]]>