{ "metadata": { "language": "fsharp", "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "###Prime digit replacements\n", "####Problem 51\n", "By replacing the 1st digit of the 2-digit number *3, it turns out that six of the nine possible values: $13, 23, 43, 53, 73$, and $83$, are all prime.\n", "\n", "By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, 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.\n", "\n", "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." ] }, { "cell_type": "code", "collapsed": false, "input": [ "open Euler\n", "\n", "let t = System.\n", "\n", "let p51() =\n", " let groups n = \n", " seq [ for x in ['0'..'9'] ->\n", " set [ for y in ['0'..'9'] -> string n |> String.map (fun c -> if c=x then y else c) |> int ]\n", " |> Set.filter Math.PrimeQ ]\n", " |> Seq.filter (fun s -> s.Count = 8)\n", " \n", " // found answer with smallest of 857 ... leading zeros not allowed\n", " // code changed to take next\n", " \n", " Math.Primes32\n", " |> Seq.collect groups\n", " |> Seq.nth 1\n", " |> Set.minElement\n", " \n", "Euler.Timer(p51)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 1, "text": [ "val it : int * float = (121313, 5.0038227)" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Permuted multiples\n", "####Problem 52\n", "It can be seen that the number, $125874$, and its double, $251748$, contain exactly the same digits, but in a different order.\n", "\n", "Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits." ] }, { "cell_type": "code", "collapsed": false, "input": [ "open Euler\n", "\n", "let p52() =\n", " let digits n = (string n).ToCharArray() |> set \n", " let sameMultiples n =\n", " let sets = [1..6] |> List.map (fun m -> digits(n*m))\n", " if sets.Tail |> List.forall((=) sets.Head) then Some n else None\n", " seq [100000..1000000]\n", " |> Seq.map sameMultiples\n", " |> Seq.find (fun n -> n.IsSome)\n", " \n", "Euler.Timer(p52)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 3, "text": [ "val it : int option * float = (Some 142857, 0.5343717)" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Combinatoric selections\n", "####Problem 53\n", "There are exactly ten ways of selecting three from five, $12345$:\n", "\n", "$123, 124, 125, 134, 135, 145, 234, 235, 245$, and $345$\n", "\n", "In combinatorics, we use the notation, $^5C_3=10$.\n", "\n", "In general,\n", "\n", "$^nC_r = \\frac {n!} {r!(n-r)!}$, where $r \u2264 n$, $n! = n\u00d7(n\u22121)\u00d7...\u00d73\u00d72\u00d71$, and $0! = 1$. It is not until $n = 23$, that a value exceeds one-million: $^{23}C_{10} = 1144066$.\n", "\n", "How many, not necessarily distinct, values of $^nC_r$, for $1 \u2264 n \u2264 100$, are greater than one-million?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "open Euler\n", "\n", "let p53() =\n", " let lnFactorial = \n", " let f n = [1.0 .. float n] |> Seq.map log |> Seq.sum\n", " Map([1..100] |> List.map (fun k -> k, f k)) \n", " let isBigger n r = \n", " lnFactorial.[n] - lnFactorial.[r] - lnFactorial.[n-r] > log 1000000. \n", " let cnt = ref 0\n", " for n = 1 to 100 do\n", " for r = 1 to n-1 do\n", " if isBigger n r then\n", " incr cnt\n", " !cnt\n", " \n", "Euler.Timer(p53)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 8, "text": [ "val it : int * float = (4075, 0.0055062)" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Poker hands\n", "####Problem 54\n", "In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:\n", "\n", "* __High Card__: Highest value card.\n", "* __One Pair__: Two cards of the same value.\n", "* __Two Pairs__: Two different pairs.\n", "* __Three of a Kind__: Three cards of the same value.\n", "* __Straight__: All cards are consecutive values.\n", "* __Flush__: All cards of the same suit.\n", "* __Full House__: Three of a kind and a pair.\n", "* __Four of a Kind__: Four cards of the same value.\n", "* __Straight Flush__: All cards are consecutive values of same suit.\n", "* __Royal Flush__: Ten, Jack, Queen, King, Ace, in same suit. \n", "\n", "The cards are valued in the order: \n", "2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.\n", "\n", "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.\n", "\n", "Consider the following five hands dealt to two players:\n", "\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
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
\n", "
\n", "\n", "The file, poker.txt, contains one-thousand 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.\n", "\n", "How many hands does Player 1 win?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "open Euler\n", "\n", "type Suit = | Heart | Club | Spade | Diamond\n", "\n", "type CardValue = | ValueCard of int | Jack | Queen | King | Ace\n", "with static member (~+) (value:CardValue) =\n", " match value with\n", " | ValueCard n -> if n < 10 then ValueCard (n+1) else Jack\n", " | Jack -> Queen | Queen -> King | King -> Ace | Ace -> ValueCard(2)\n", "\n", "type Card = { Value:CardValue; Suit:Suit }\n", "\n", "type Rank =\n", " | HighCard of CardValue\n", " | OnePair of CardValue\n", " | TwoPairs of CardValue * CardValue\n", " | Three of CardValue\n", " | Straight of CardValue // highest value card\n", " | Flush\n", " | FullHouse of CardValue * CardValue\n", " | Four of CardValue\n", " | StraightFlush of CardValue // highest value card & suit\n", " | RoyalFlush\n", "\n", "let p54() =\n", " let isSameSuit (cards:Card list) = cards |> List.forall (fun c -> c.Suit = cards.Head.Suit)\n", " let getHighestCard(cards:Card list) = cards |> List.maxBy (fun card -> card.Value)\n", " let isStraight (cards:Card list) =\n", " let flag = cards |> List.sort |> Seq.windowed 2\n", " |> Seq.forall (fun c -> c.[1].Value = +c.[0].Value)\n", " (flag, getHighestCard cards) \n", " let getDupes (cards:Card list) =\n", " cards\n", " |> Seq.groupBy (fun card -> card.Value)\n", " |> Seq.map (fun (k, seq) -> (k, Seq.length seq))\n", " |> Seq.filter (fun (k, len) -> len > 1)\n", " |> Seq.toList\n", " let evaluateHand (cards:Card list) =\n", " let (isStraight, highCard) = isStraight cards\n", " let sameSuit = isSameSuit cards \n", " if sameSuit && isStraight && highCard.Value = Ace then RoyalFlush\n", " else if sameSuit && isStraight then StraightFlush(highCard.Value)\n", " else if sameSuit then Flush\n", " else if isStraight then Straight(highCard.Value)\n", " else\n", " let dupes = getDupes cards\n", " if dupes.Length = 0 then HighCard(highCard.Value)\n", " else if dupes.Length = 1 then\n", " match dupes.[0] with\n", " | (cardValue,2) -> OnePair(cardValue)\n", " | (cardValue,3) -> Three(cardValue)\n", " | (cardValue,4) -> Four(cardValue)\n", " | _ -> failwith \"error\"\n", " else\n", " match dupes with\n", " | [(cardValue',2);(cardValue'',2)] -> TwoPairs(cardValue', cardValue'')\n", " | [(cardValue',3);(cardValue'',2)] -> FullHouse(cardValue', cardValue'')\n", " | [(cardValue',2);(cardValue'',3)] -> FullHouse(cardValue'', cardValue') \n", " | _ -> failwith \"error\"\n", " let isP1Winner (p1:Card list) (p2:Card list) =\n", " let p1Rank, p2Rank = evaluateHand p1, evaluateHand p2 \n", " if p1Rank > p2Rank then true\n", " else if p1Rank = p2Rank then\n", " let rec compareHighCard (p1':Card list) (p2':Card list) =\n", " let p1'HighCard, p2'HighCard = getHighestCard p1', getHighestCard p2'\n", " if p1'HighCard.Value > p2'HighCard.Value then true\n", " else if p1'HighCard.Value = p2'HighCard.Value then\n", " let p1'' = p1' |> List.filter (fun c -> c.Value < p1'HighCard.Value)\n", " let p2'' = p2' |> List.filter (fun c -> c.Value < p2'HighCard.Value)\n", " compareHighCard p1'' p2''\n", " else false \n", " compareHighCard p1 p2\n", " else false \n", " let parseCard (s:string) =\n", " let value = s.[0]\n", " let cardValue =\n", " match value with\n", " | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' -> ValueCard(int(value.ToString()))\n", " | 'T' -> ValueCard(10) | 'J' -> Jack | 'Q' -> Queen | 'K' -> King | 'A' -> Ace |_ -> failwith \"error\"\n", " let suit =\n", " match s.Chars(1) with\n", " | 'S' -> Spade | 'H' -> Heart | 'D' -> Diamond | 'C' -> Club |_ -> failwith \"error\"\n", " { Card.Value=cardValue; Suit=suit } \n", " let hands =\n", " let raw = Euler.ReadDelimitedFile(__SOURCE_DIRECTORY__ + \"/txt/p054.txt\",' ')\n", " [| for row in raw -> row |> Array.map parseCard |] \n", " let p1Hands = hands |> Array.map (fun cards -> cards |> Seq.take 5 |> Seq.toList)\n", " let p2Hands = hands |> Array.map (fun cards -> cards |> Seq.skip 5 |> Seq.toList) \n", " Array.map2 (fun p1 p2 -> isP1Winner p1 p2) p1Hands p2Hands\n", " |> Array.filter (fun b -> b)\n", " |> Array.length\n", " \n", "Euler.Timer(p54)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 3, "text": [ "val it : int * float = (376, 0.0589704)" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Lychrel numbers\n", "####Problem 55\n", "\n", "If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.\n", "\n", "Not all numbers produce palindromes so quickly. For example,\n", "\n", "$$349 + 943 = 1292$$\n", "$$1292 + 2921 = 4213$$\n", "$$4213 + 3124 = 7337$$\n", "\n", "That is, $349$ took three iterations to arrive at a palindrome.\n", "\n", "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 ten-thousand, 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, 28-digits).\n", "\n", "Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is $4994$.\n", "\n", "How many Lychrel numbers are there below ten-thousand?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "open Euler\n", "\n", "let p55() =\n", " let rev (n:bigint) = Math.Reverse(n)\n", " let isPalindrome n = rev n = n \n", " let isLychrel n =\n", " let rec loop i acc =\n", " let next = acc + rev acc\n", " if isPalindrome next then false\n", " elif i > 50 then true\n", " else loop (i+1) next\n", " loop 1 n \n", " [ 1I .. 10000I] |> List.filter isLychrel |> List.length\n", "\n", "Euler.Timer(p55)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 1, "text": [ "val it : int * float = (249, 0.1984683)" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Powerful digit sum\n", "####Problem 56\n", "A googol ($10^{100}$) is a massive number: one followed by one-hundred zeros; $100^{100}$ is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.\n", "\n", "Considering natural numbers of the form, $a^b$, where $a, b < 100$, what is the maximum digital sum?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "open Euler\n", "\n", "let p56() =\n", " let digitSum (a:int) (b:int) =\n", " bigint.Pow(bigint a, b) \n", " |> fun n -> (string n).ToCharArray()\n", " |> Array.sumBy (fun c -> int c - 48)\n", " \n", " [ for a = 1 to 100 do\n", " for b = 1 to 100 do\n", " yield digitSum a b ]\n", " |> List.max\n", "\n", "Euler.Timer(p56)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 2, "text": [ "val it : int * float = (972, 0.035884)" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Square root convergents\n", "####Problem 57\n", "It is possible to show that the square root of two can be expressed as an infinite continued fraction.\n", "\n", "$$\u221a 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...$$\n", "\n", "By expanding this for the first four iterations, we get:\n", "\n", "$$1 + 1/2 = 3/2 = 1.5$$\n", "$$1 + 1/(2 + 1/2) = 7/5 = 1.4$$\n", "$$1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...$$\n", "$$1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...$$\n", "\n", "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.\n", "\n", "In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "open Euler\n", "// uses a BigRational type\n", "\n", "let p57() =\n", " let next n = 1Q + (n+1Q).Inverse\n", " let digits n = (string n).ToCharArray() |> Seq.length \n", " let cnt = ref 0\n", " let n = ref (next 1Q) \n", " for i = 1 to 1000 do\n", " if digits((!n).Numerator) > digits((!n).Denominator) then\n", " incr cnt\n", " n := next (!n)\n", " !cnt\n", " \n", "Euler.Timer(p57)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 1, "text": [ "val it : int * float = (153, 0.027241)" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Spiral primes\n", "####Problem 58\n", "Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.\n", "\n", "

37 36 35 34 33 32 31
\n", "38 17 16 15 14 13 30
\n", "39 18  5  4  3 12 29
\n", "40 19  6  1  2 11 28
\n", "41 20  7  8  9 10 27
\n", "42 21 22 23 24 25 26
\n", "43 44 45 46 47 48 49

\n", "\n", "\n", "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 \u2248 62%.\n", "\n", "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%?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "open Euler\n", "\n", "let p58() =\n", " let rec loop total primes size =\n", " let newPrimes = \n", " [0..3] |> List.map(fun n -> size*size - n*(size-1))\n", " |> List.filter Math.PrimeQ\n", " |> List.length\n", " |> (+) primes\n", " let newTotal = total+4\n", " let newSize = size+2\n", " if newPrimes * 10 < newTotal then size\n", " else loop newTotal newPrimes newSize\n", " loop 1 0 3\n", " \n", "Euler.Timer(p58)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 2, "text": [ "val it : int * float = (26241, 4.9358527)" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###XOR decryption\n", "####Problem 59\n", "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.\n", "\n", "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.\n", "\n", "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.\n", "\n", "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.\n", "\n", "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." ] }, { "cell_type": "code", "collapsed": false, "input": [ "open System\n", "open Euler\n", "\n", "let p59() =\n", " let encrypted = \n", " Euler.ReadDelimitedFile(__SOURCE_DIRECTORY__ + \"/txt/p059.txt\",',')\n", " |> Array.concat\n", " |> Array.map byte\n", " \n", " let isValidChar c =\n", " let ch = char(c)\n", " Char.IsLetterOrDigit(ch) || Char.IsPunctuation(ch) || Char.IsSeparator(ch)\n", " \n", " let tryDecipher (key:byte[]) =\n", " let decrypted = encrypted |> Array.mapi (fun i b -> b ^^^ key.[i%key.Length])\n", " match decrypted |> Seq.forall isValidChar with\n", " |true -> Some <| String(decrypted |> Array.map char)\n", " |false -> None\n", " \n", " let decrypted =\n", " seq [ for a in 'a'..'z' do\n", " for b in 'a'..'z' do\n", " for c in 'a'..'z' ->\n", " tryDecipher [| byte a; byte b; byte c |] ]\n", " |> Seq.find (fun m -> m.IsSome)\n", " |> fun m -> m.Value\n", " \n", " decrypted |> Seq.sumBy (byte >> int)\n", " \n", "Euler.Timer(p59)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 3, "text": [ "val it : int * float = (107359, 0.1407496)" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Prime pair sets\n", "####Problem 60\n", "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.\n", "\n", "Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime." ] }, { "cell_type": "code", "collapsed": false, "input": [ "open Euler\n", "\n", "let p60() =\n", " let concat a b = b + a * pown 10L (1+int(log10(float b)))\n", " let testPair a b = Math.PrimeQ(concat a b) && Math.PrimeQ(concat b a)\n", " \n", " // assuming answer will under 10000\n", " let maxN = Math.PrimePi 10000\n", " \n", " let init = \n", " seq { for a in 4..maxN -> [Math.Prime a], a }\n", " \n", " let next (prior:int64 list, a:int) =\n", " seq { for b in a+1..maxN ->\n", " (Math.Prime b)::prior, b }\n", " |> Seq.filter (fun (s,_) -> s.Tail |> Seq.forall (testPair s.Head))\n", " \n", " init \n", " |> Seq.collect next // 2 primes\n", " |> Seq.collect next // 3 primes\n", " |> Seq.collect next // 4 primes\n", " |> Seq.collect next // 5 primes\n", " |> Seq.head\n", " |> fst \n", " |> Seq.sum\n", " \n", "Euler.Timer(p60)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 1, "text": [ "val it : int64 * float = (26033L, 39.809968)" ] } ], "prompt_number": 1 } ], "metadata": {} } ] }