The post Project Euler 95 Solution appeared first on Dreamshire.
]]>Project Euler 95: The proper divisors of a number are all the divisors excluding the number itself. For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. As the sum of these divisors is equal to 28, we call it a perfect number.
Interestingly the sum of the proper divisors of 220 is 284 and the sum of the proper divisors of 284 is 220, forming a chain of two numbers. For this reason, 220 and 284 are called an amicable pair.
Perhaps less well known are longer chains. For example, starting with 12496, we form a chain of five numbers:
12496 → 14288 → 15472 → 14536 → 14264 (→ 12496 → …)
Since this chain returns to its starting point, it is called an amicable chain.
Find the smallest member of the longest amicable chain with no element exceeding one million.
A very straightforward approach that follows a logical flow similar to problem 21 by sieving the sum of divisors instead of using a function to calculate them.
1. Sieve a set of divisors for all numbers up to the limit. Uses a bunch of memory which is a drawback to solving larger problems. But I can mostly guess what the answer is for 10^{99} because things don’t really change much.
2. The easy part is to calculate successive members of the chain and slice it where the chain begins to repeat.
3. Collect the smallest member for each new increasing chain length.
4. Print out the results.
The easy way from learning by doing it the hard way:
Real solution that helped show a pattern:
The post Project Euler 95 Solution appeared first on Dreamshire.
]]>The post Project Euler 93 Solution appeared first on Dreamshire.
]]>By using each of the digits from the set, {1, 2, 3, 4}, exactly once, and making use of the four arithmetic operations (+, −, *, /) and brackets/parentheses, it is possible to form different positive integer targets.
For example,
8 = (4 * (1 + 3)) / 2
14 = 4 * (3 + 1 / 2)
19 = 4 * (2 + 3) − 1
36 = 3 * 4 * (2 + 1)
Note that concatenations of the digits, like 12 + 34, are not allowed.
Using the set, {1, 2, 3, 4}, it is possible to obtain thirtyone different target numbers of which 36 is the maximum, and each of the numbers 1 to 28 can be obtained before encountering the first nonexpressible number.
Find the set of four distinct digits, a < b < c < d, for which the longest set of consecutive positive integers, 1 to n, can be obtained, giving your answer as a string: abcd.
Well, this is just a complicated conglomeration of combinations, permutations and products of expressions that quickly finds a maximum sequence size and the associated terms that yield that maximum.
1. Define combinations of terms using the integers from 1 to 9. There aren’t that many, just 126 sets from (1,2,3,4) to (6, 7, 8, 9).
2. Permute each combination. (1,2,3,4), (1,2,4,3), (1,4,2,3), etc.
3. Create an iterator of operators using the product method that look like (+++, ++*, ++, ++/, +*+, etc.) and calculate each expression in such a way that we avoid a div by zero. Oh, BTW, use truediv instead of div, that cost me some time not knowing the difference.
4. Collect a maximum sequence size, and sequence length.
5. Fin. This was a bit difficult to get my head around at first, but just stated coding and it fell together. Yeah, there are only two equations required – not five. Graph the possibilities and check out the relationship between nodes. This works perfectly to solve this problem.
The post Project Euler 93 Solution appeared first on Dreamshire.
]]>The post Project Euler 98 Solution appeared first on Dreamshire.
]]>Project Euler 98: By replacing each of the letters in the word CARE with 1, 2, 9, and 6 respectively, we form a square number: 1296 = 36^{2}. What is remarkable is that, by using the same digital substitutions, the anagram, RACE, also forms a square number: 9216 = 96^{2}. We shall call CARE (and RACE) a square anagram word pair and specify further that leading zeroes are not permitted, neither may a different letter have the same digital value as another letter.
Using words.txt (right click and ‘Save Link/Target As…’), a 16K text file containing nearly twothousand common English words, find all the square anagram word pairs (a palindromic word is NOT considered to be an anagram of itself).
What is the largest square number formed by any member of such a pair?
NOTE: All anagrams formed must be contained in the given text file.
A simple and straightforward implementation that performs as follows:
1. Read words into a list from network resource. Trim first and last quote characters. Store each word as a tuple: the word and a list of the sorted letters in the word. Ignore words shorter than 5 letters (ignoring quotes).
2. Build anagram word pair list for the word list. Clearly, 3 and fewer letter words are noncontenders, nor are 4 letter words. We are given 96^{2}, and 97^{2}, 98^{2}, and 99^{2} wouldn’t work because they repeat a digit or contain the dreaded zero and unable to leave a maximum greater than the given 9216.
3. Find all combinations of values using the pattern set in word’s anagram. You could check duplicate patterns for the same words size and ignore those, but I didn’t do that. Also note that I’m convinced zero will never be a factor.
4. Collect maximum square values for an ultimate global maximum.
5. Print the maximum.
from collections import defaultdict
for digits in range(3,14):
d = defaultdict(list)
for i in xrange(int((10**(digits1))**0.5), int((10**digits)**0.5)+1):
j = ''.join(sorted(str(i*i)))
d[j].append(i)
max_key = max(d, key= lambda x: len(set(d[x])))
print d[max_key][1]**2
The post Project Euler 98 Solution appeared first on Dreamshire.
]]>The post Project Euler 83 Solution appeared first on Dreamshire.
]]>Project Euler 83 NOTE: This problem is a significantly more challenging version of Problem 81.
In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, is indicated in bold red and is equal to 2297.
131  673  234  103  18 
201  96  342  965  150 
630  803  746  422  111 
537  699  497  121  956 
805  732  524  37  331 
Find the minimal path sum, in matrix.txt (right click and “Save Link/Target As…”), a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right by moving left, right, up, and down.
This problem is more complex than problems 81 and 82. We are still trying to find a minimum path sum from the topright corner to the bottomleft corner but are now allowed to move left in addition to up, down and right. This rules out a dynamic approach as we cannot look left.
Fortunately, we have a great package for Python call networkx. It allows us to build a directed graph of the matrix and specify a start location (source=(0,0)), a target location (target=(n1,m1)) and a method for solving (Astar or Dijkstra). The directions are up(1,0), down(+1,0), right(0,+1) and left(0,1) when valid.
Our solution is now reduced to:
We read the data into a matrix from a URL resource as before and build a simple graph. The neighbors
array is a device to list the neighbors for each cell and exclude any that lie outside the matrix. Edges are added for each cell with the contents used as a weight.
All thatâ€™s left is to send it to the package and await the result.
The post Project Euler 83 Solution appeared first on Dreamshire.
]]>The post Project Euler 94 Solution appeared first on Dreamshire.
]]>Project Euler 94: It is easily proved that no equilateral triangle exists with integral length sides and integral area. However, the almost equilateral triangle 556 has an area of 12 square units.
We shall define an almost equilateral triangle to be a triangle for which two sides are equal and the third differs by no more than one unit.
Find the sum of the perimeters of all almost equilateral triangles with integral side lengths and area and whose perimeters do not exceed one billion (1,000,000,000).
A good magic trick seems to defy both logic and physics until the secret is revealed. Then your response is something like: “What? That’s it! You just stacked the deck? I can’t believe I fell for that!” But until that point you were truly impressed.
Such are the secrets of these infernal math problems. I usually have few clues knowing where to begin and after some research and study I hack together a few short lines of code and wonder: “How is it I didn’t see that two hours ago?”
Anyway, here’s the solution to this problem of isoscele triangles trying to masquerade as “almost equilaterals.” Resources include Wikipedia’s article Almostequilateral Heronian triangles, the series Reference: The OnLine Encyclopedia of Integer Sequences (OEIS) : Areas of 'closetoequilateral' integer triangles, and the table below in the comments section which yields some evidence of a sequence and the recurrence equation wrapped in a Diophantine equation that guarantee integer results.
Adding ±1 to the perimeter guarantees an even area and perimeter as the problem requires.
Side 1 (a)  Side 2 (a)  Side 3 (b=a±1)  Perimeter  Area 

5  5  6  16  12 
17  17  16  50  120 
65  65  66  196  1848 
241  241  240  722  25080 
901  901  902  2704  351780 
3361  3361  3360  10082  4890480 
12545  12545  12546  37636  68149872 
46817  46817  46816  140450  949077360 
174725  174725  174726  524176  13219419708 
652081  652081  652080  1956242  184120982760 
2433601  2433601  2433602  7300804  2564481115560 
9082321  9082321  9082320  27246962  35718589344360 
33895685  33895685  33895686  101687056  497495864091732 
126500417  126500417  126500416  379501250  6929223155685600 
The post Project Euler 94 Solution appeared first on Dreamshire.
]]>The post Project Euler 91 Solution appeared first on Dreamshire.
]]>Project Euler 91: The points P (x_{1}, y_{1}) and Q (x_{2}, y_{2}) are plotted at integer coordinates and are joined to the origin, O(0,0), to form ΔOPQ.
There are exactly fourteen triangles containing a right angle that can be formed when each coordinate lies between 0 and 2 inclusive; that is,
0 ≤ x_{1}, y_{1}, x_{2}, y_{2} ≤ 2.
Given that 0 ≤ x_{1}, y_{1}, x_{2}, y_{2} ≤ 50, how many right triangles can be formed?
There is a hyper series here…somewhere.
Data Table 1. Number of triangles from 0 ≤ x_{1}, y_{1}, x_{2}, y_{2} ≤ {1..10}.
N  # Triangles 

1  3 
2  14 
3  33 
4  62 
5  101 
6  148 
7  207 
8  276 
9  353 
10  448 
Now, we can remove 3n^{2} known triangles that have an edge on either axis.
Data Table 2. Number of triangles as above but with 3n^{2} contributing to sum
N  3N^{2}  From some other source  # Triangles 

1  3  0  3 
2  12  2  14 
3  27  6  33 
4  48  14  62 
5  75  26  101 
6  108  40  148 
7  147  60  207 
8  192  84  276 
9  243  110  353 
10  300  148  448 
Data Table 3. Number of triangles as above but with N^{2}/2 contributing to sum
N  3N^{2}  N^{2}/2  From some other source  # Triangles 

1  3  0  0  3 
2  12  2  0  14 
3  27  4  2  33 
4  48  8  6  62 
5  75  12  14  101 
6  108  18  22  148 
7  147  24  36  207 
8  192  32  52  276 
9  243  40  70  353 
10  300  50  98  448 
Well, brute force until I figure out the series, which seems trivial but so far elusive. Still, good enough for even a more challenging problem set from HackerRank.
The post Project Euler 91 Solution appeared first on Dreamshire.
]]>The post Project Euler 96 Solution appeared first on Dreamshire.
]]>Project Euler 96: Su Doku (Japanese meaning number place) is the name given to a popular puzzle concept. Its origin is unclear, but credit must be attributed to Leonhard Euler who invented a similar, and much more difficult, puzzle idea called Latin Squares. The objective of Su Doku puzzles, however, is to replace the blanks (or zeros) in a 9 by 9 grid in such that each row, column, and 3 by 3 box contains each of the digits 1 to 9. Below is an example of a typical starting puzzle grid and its solution grid.


A well constructed Su Doku puzzle has a unique solution and can be solved by logic, although it may be necessary to employ "guess and test" methods in order to eliminate options (there is much contested opinion over this). The complexity of the search determines the difficulty of the puzzle; the example above is considered easy because it can be solved by straight forward direct deduction.
The 6K text file, sudoku.txt (right click and ‘Save Link/Target As…’), contains fifty different Su Doku puzzles ranging in difficulty, but all with unique solutions (the first puzzle in the file is the example above).
By solving all fifty puzzles find the sum of the 3digit numbers found in the top left corner of each solution grid; for example, 483 is the 3digit number found in the top left corner of the solution grid above.
Read an external file and parse into required format, solve Sudoku puzzles and add the first 3 digits: All in under 30 lines of Python.
Input file:
Each puzzle was converted from it’s native form into a string of 81 integers where zeros are blank squares. Any line with the word ‘Grid’ was ignored. The supplied data has been prevalidated, so sanity checks are not performed. Here’s an example for the puzzle listed in the problem description:
Grid 01
003020600
900305001
001806400
008102900
700000008
006708200
002609500
800203009
005010300
And here is what the solver expects:
003020600900305001001806400008102900700000008006708200002609500800203009005010300
For more information on this concise solution consult:
Shortest Python Sudoku solver
The post Project Euler 96 Solution appeared first on Dreamshire.
]]>The post Project Euler 90 Solution appeared first on Dreamshire.
]]>Each of the six faces on a cube has a different digit (0 to 9) written on it; the same is done to a second cube. By placing the two cubes sidebyside in different positions we can form a variety of 2digit numbers.
For example, the square number 64 could be formed:
In fact, by carefully choosing the digits on both cubes it is possible to display all of the square numbers below onehundred: 01, 04, 09, 16, 25, 36, 49, 64, and 81.
For example, one way this can be achieved is by placing {0, 5, 6, 7, 8, 9} on one cube and {1, 2, 3, 4, 8, 9} on the other cube.
However, for this problem we shall allow the 6 or 9 to be turned upsidedown so that an arrangement like {0, 5, 6, 7, 8, 9} and {1, 2, 3, 4, 6, 7} allows for all nine square numbers to be displayed; otherwise it would be impossible to obtain 09.
In determining a distinct arrangement we are interested in the digits on each cube, not the order.
{1, 2, 3, 4, 5, 6} is equivalent to {3, 6, 4, 1, 2, 5}
{1, 2, 3, 4, 5, 6} is distinct from {1, 2, 3, 4, 5, 9}
But because we are allowing 6 and 9 to be reversed, the two distinct sets in the last example both represent the extended set {1, 2, 3, 4, 5, 6, 9} for the purpose of forming 2digit numbers.
How many distinct arrangements of the two cubes allow for all of the square numbers to be displayed?
Let’s reword this problem a bit:
Take two cubes and inscribe every side with six numbers from the set {09} in such a way that when they are placed sidebyside they show every perfect square from the set {01, 04, 09, 16, 25, 36, 49, 64, 81}.
As an example, one possibility could be {0, 5, 6, 7, 8, 9} on one cube and {1, 2, 3, 4, 8, 9} on the other. The cubes can be positioned in any way that forms the perfect square. Also, a cube with the combination {9, 8, 7, 0, 5, 6} is the same as (NOT distinct from) another cube with the same numbers but in a different order {0, 5, 6, 7, 8, 9}.
To make the problem a bit more challenging, let’s say that you can turn a cube upside down so the 6 could serve as a 9. This makes the numbers to inscribe on the cube as {0, 1, 2, 3, 4, 5, 6, 7, 8, 6}.
How many distinct arrangements of the two cubes allow for all of the square numbers to be displayed?
To solve this problem we are going to use:
Stepbystep analysis:
Firstly, we create a list of desired outcomes that include (0,1), (0,4), (0,6)^{*}, (1,6), (2,5), (3,6), (4,6)^{*}, and (8,1). Note that (6,4) is missing because the cubes can be set sidebyside in either way so (4,6) is the same as (6,4).
^{*}(the 6 can be flipped for a 9)
Secondly, we build a list of tuples (which didn’t need to be tuples, but they looked cleaner in source) for all the possibilities of 10 numbers chosen 6 at a time. This is _{10}C_{6} or 210 possible combinations.
As this may be confusing, here is a simplified version to look at using 4 numbers chosen 2 at a time (_{4}C_{2} or 6 possible combinations):
>>> from itertools import combinations
>>> cube = list(combinations([0,1,2,3], 2))
>>> cube
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
>>>
Notice that the combination function produces a list of tuples for each iteration.
We’ll hold off on the valid function for a moment and focus on the double list comprehension.
The enumerate function is a cleaner and more efficient way of replacing:
for n in range(len(my_list)):
print n, my_list[n]
with:
for n, item in enumerate(my_list):
print n, item
So, enumerate returns both the index and the element. This is useful for comparing every item in a list to every other item in the list. Here’s an example continuing from above:
for i,c1 in enumerate(cube):
print 'first loop',i,c1
for c2 in cube[:i]:
print " second loop", i,c2
Output:
first loop 0 (0, 1) first loop 1 (0, 2) second loop 1 (0, 1) first loop 2 (0, 3) second loop 2 (0, 1) second loop 2 (0, 2) first loop 3 (1, 2) second loop 3 (0, 1) second loop 3 (0, 2) second loop 3 (0, 3) first loop 4 (1, 3) second loop 4 (0, 1) second loop 4 (0, 2) second loop 4 (0, 3) second loop 4 (1, 2) first loop 5 (2, 3) second loop 5 (0, 1) second loop 5 (0, 2) second loop 5 (0, 3) second loop 5 (1, 2) second loop 5 (1, 3)
Thirdly, the valid function simply returns True for those cases that a square can be made from a perspective set of two cubes in either direction. The all function will return True only if all the generated list items are True.
Lastly, all that’s left to do is count valid combinations. Duplicates are ignored inherently by only checking a possible cube against all other combinations that come before it. That’s why we use cube[:i] in the second loop and not just cube. Which is also why enumerate is so nice, because it gives us the index, i.
By changing these two lines:
squares = [(0,1), (0,4), (0,9), (1,6), (2,5), (3,6), (4,9), (6,4), (8,1)]
dice = list(combinations([0,1,2,3,4,5,6,7,8,9], 6))
The answer would be: 205
The post Project Euler 90 Solution appeared first on Dreamshire.
]]>The post Project Euler 88 Solution appeared first on Dreamshire.
]]>A natural number, N, that can be written as the sum and product of a given set of at least two natural numbers, {a_{1}, a_{2}, … , a_{k}} is called a productsum number: N = a_{1} + a_{2} + … + a_{k} = a_{1} × a_{2} × … × a_{k}.
For example, 6 = 1 + 2 + 3 = 1 × 2 × 3.
For a given set of size, k, we shall call the smallest N with this property a minimal productsum number. The minimal productsum numbers for sets of size, k = 2, 3, 4, 5, and 6 are as follows.
k=2: 4 = 2 × 2 = 2 + 2
k=3: 6 = 1 × 2 × 3 = 1 + 2 + 3
k=4: 8 = 1 × 1 × 2 × 4 = 1 + 1 + 2 + 4
k=5: 8 = 1 × 1 × 2 × 2 × 2 = 1 + 1 + 2 + 2 + 2
k=6: 12 = 1 × 1 × 1 × 1 × 2 × 6 = 1 + 1 + 1 + 1 + 2 + 6
Hence for 2≤k≤6, the sum of all the minimal productsum numbers is 4+6+8+12 = 30; note that 8 is only counted once in the sum.
In fact, as the complete set of minimal productsum numbers for 2≤k≤12 is {4, 6, 8, 12, 15, 16}, the sum is 61.
What is the sum of all the minimal productsum numbers for 2≤k≤12000?
Our original DP solution markedly improved with ideas from the PE forums. This is very similar to Euler’s solution with improved timing and storage.
The post Project Euler 88 Solution appeared first on Dreamshire.
]]>The post Project Euler 92 Solution appeared first on Dreamshire.
]]>Project Euler 92: A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.
For example,
44 → 32 → 13 → 10 → 1 → 1
85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.
How many starting numbers below ten million will arrive at 89?
Project Euler 92: To begin, all chains that end in 1 are called happy numbers. Any chain that contains 89 or 4 will be destined to an endless loop of calculations and forever remain unhappy. Here’s more information from Wikipedia: Happy number
It would seem a simple task to loop through all 10^{7} numbers, calculate a chain for each one and count those that reach 89 or 4. This can, in fact, be done in less than a minute, but falls short for trying a limit of 10^{99} instead.
So, several optimizations can be ferreted out quickly when you realize that there are only 495 possible ways a number from 1 – 10^{7} can have it’s digits squared and summed. The range for these numbers is 1 to 567 (9^{2} * 7).
This means that any number in the target range of 1 – 10^{7} can be looked up from a small table that determines ahead of time which number will be happy or not. By extension, as we learned from Kristian’s excellent Math Blog is to take similar “digited” numbers and simply add the multinomial coefficient to include all permutations of that number.
For example, 424501 is the same result of the sum of the square of the digits as is 244501, 501244, (0)12445, etc. In fact there are a total of 2520 combinations instead of 5040:
If we only check 576 numbers and calculate the multinomial coefficient instead of adding 1 by checking all 10,000,000 we save many iterations and are able to calculate much more challenging limits, especially 10^{99}.
This problem was solved using these ideas and dynamic programming in logarithmic time.
The post Project Euler 92 Solution appeared first on Dreamshire.
]]>