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.
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.
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.
open Euler
let t = System.
let p51() =
let groups n =
seq [ for x in ['0'..'9'] ->
set [ for y in ['0'..'9'] -> string n |> String.map (fun c -> if c=x then y else c) |> int ]
|> Set.filter Math.PrimeQ ]
|> Seq.filter (fun s -> s.Count = 8)
// found answer with smallest of 857 ... leading zeros not allowed
// code changed to take next
Math.Primes32
|> Seq.collect groups
|> Seq.nth 1
|> Set.minElement
Euler.Timer(p51)
val it : int * float = (121313, 5.0038227)
open Euler
let p52() =
let digits n = (string n).ToCharArray() |> set
let sameMultiples n =
let sets = [1..6] |> List.map (fun m -> digits(n*m))
if sets.Tail |> List.forall((=) sets.Head) then Some n else None
seq [100000..1000000]
|> Seq.map sameMultiples
|> Seq.find (fun n -> n.IsSome)
Euler.Timer(p52)
val it : int option * float = (Some 142857, 0.5343717)
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, $^5C_3=10$.
In general,
$^nC_r = \frac {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 one-million: $^{23}C_{10} = 1144066$.
How many, not necessarily distinct, values of $^nC_r$, for $1 ≤ n ≤ 100$, are greater than one-million?
open Euler
let p53() =
let lnFactorial =
let f n = [1.0 .. float n] |> Seq.map log |> Seq.sum
Map([1..100] |> List.map (fun k -> k, f k))
let isBigger n r =
lnFactorial.[n] - lnFactorial.[r] - lnFactorial.[n-r] > log 1000000.
let cnt = ref 0
for n = 1 to 100 do
for r = 1 to n-1 do
if isBigger n r then
incr cnt
!cnt
Euler.Timer(p53)
val it : int * float = (4075, 0.0055062)
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 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.
How many hands does Player 1 win?
open Euler
type Suit = | Heart | Club | Spade | Diamond
type CardValue = | ValueCard of int | Jack | Queen | King | Ace
with static member (~+) (value:CardValue) =
match value with
| ValueCard n -> if n < 10 then ValueCard (n+1) else Jack
| Jack -> Queen | Queen -> King | King -> Ace | Ace -> ValueCard(2)
type Card = { Value:CardValue; Suit:Suit }
type Rank =
| HighCard of CardValue
| OnePair of CardValue
| TwoPairs of CardValue * CardValue
| Three of CardValue
| Straight of CardValue // highest value card
| Flush
| FullHouse of CardValue * CardValue
| Four of CardValue
| StraightFlush of CardValue // highest value card & suit
| RoyalFlush
let p54() =
let isSameSuit (cards:Card list) = cards |> List.forall (fun c -> c.Suit = cards.Head.Suit)
let getHighestCard(cards:Card list) = cards |> List.maxBy (fun card -> card.Value)
let isStraight (cards:Card list) =
let flag = cards |> List.sort |> Seq.windowed 2
|> Seq.forall (fun c -> c.[1].Value = +c.[0].Value)
(flag, getHighestCard cards)
let getDupes (cards:Card list) =
cards
|> Seq.groupBy (fun card -> card.Value)
|> Seq.map (fun (k, seq) -> (k, Seq.length seq))
|> Seq.filter (fun (k, len) -> len > 1)
|> Seq.toList
let evaluateHand (cards:Card list) =
let (isStraight, highCard) = isStraight cards
let sameSuit = isSameSuit cards
if sameSuit && isStraight && highCard.Value = Ace then RoyalFlush
else if sameSuit && isStraight then StraightFlush(highCard.Value)
else if sameSuit then Flush
else if isStraight then Straight(highCard.Value)
else
let dupes = getDupes cards
if dupes.Length = 0 then HighCard(highCard.Value)
else if dupes.Length = 1 then
match dupes.[0] with
| (cardValue,2) -> OnePair(cardValue)
| (cardValue,3) -> Three(cardValue)
| (cardValue,4) -> Four(cardValue)
| _ -> failwith "error"
else
match dupes with
| [(cardValue',2);(cardValue'',2)] -> TwoPairs(cardValue', cardValue'')
| [(cardValue',3);(cardValue'',2)] -> FullHouse(cardValue', cardValue'')
| [(cardValue',2);(cardValue'',3)] -> FullHouse(cardValue'', cardValue')
| _ -> failwith "error"
let isP1Winner (p1:Card list) (p2:Card list) =
let p1Rank, p2Rank = evaluateHand p1, evaluateHand p2
if p1Rank > p2Rank then true
else if p1Rank = p2Rank then
let rec compareHighCard (p1':Card list) (p2':Card list) =
let p1'HighCard, p2'HighCard = getHighestCard p1', getHighestCard p2'
if p1'HighCard.Value > p2'HighCard.Value then true
else if p1'HighCard.Value = p2'HighCard.Value then
let p1'' = p1' |> List.filter (fun c -> c.Value < p1'HighCard.Value)
let p2'' = p2' |> List.filter (fun c -> c.Value < p2'HighCard.Value)
compareHighCard p1'' p2''
else false
compareHighCard p1 p2
else false
let parseCard (s:string) =
let value = s.[0]
let cardValue =
match value with
| '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' -> ValueCard(int(value.ToString()))
| 'T' -> ValueCard(10) | 'J' -> Jack | 'Q' -> Queen | 'K' -> King | 'A' -> Ace |_ -> failwith "error"
let suit =
match s.Chars(1) with
| 'S' -> Spade | 'H' -> Heart | 'D' -> Diamond | 'C' -> Club |_ -> failwith "error"
{ Card.Value=cardValue; Suit=suit }
let hands =
let raw = Euler.ReadDelimitedFile<string>(__SOURCE_DIRECTORY__ + "/txt/p054.txt",' ')
[| for row in raw -> row |> Array.map parseCard |]
let p1Hands = hands |> Array.map (fun cards -> cards |> Seq.take 5 |> Seq.toList)
let p2Hands = hands |> Array.map (fun cards -> cards |> Seq.skip 5 |> Seq.toList)
Array.map2 (fun p1 p2 -> isP1Winner p1 p2) p1Hands p2Hands
|> Array.filter (fun b -> b)
|> Array.length
Euler.Timer(p54)
val it : int * float = (376, 0.0589704)
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 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).
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is $4994$.
How many Lychrel numbers are there below ten-thousand?
open Euler
let p55() =
let rev (n:bigint) = Math.Reverse(n)
let isPalindrome n = rev n = n
let isLychrel n =
let rec loop i acc =
let next = acc + rev acc
if isPalindrome next then false
elif i > 50 then true
else loop (i+1) next
loop 1 n
[ 1I .. 10000I] |> List.filter isLychrel |> List.length
Euler.Timer(p55)
val it : int * float = (249, 0.1984683)
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.
Considering natural numbers of the form, $a^b$, where $a, b < 100$, what is the maximum digital sum?
open Euler
let p56() =
let digitSum (a:int) (b:int) =
bigint.Pow(bigint a, b)
|> fun n -> (string n).ToCharArray()
|> Array.sumBy (fun c -> int c - 48)
[ for a = 1 to 100 do
for b = 1 to 100 do
yield digitSum a b ]
|> List.max
Euler.Timer(p56)
val it : int * float = (972, 0.035884)
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 one-thousand expansions, how many fractions contain a numerator with more digits than denominator?
open Euler
// uses a BigRational type
let p57() =
let next n = 1Q + (n+1Q).Inverse
let digits n = (string n).ToCharArray() |> Seq.length
let cnt = ref 0
let n = ref (next 1Q)
for i = 1 to 1000 do
if digits((!n).Numerator) > digits((!n).Denominator) then
incr cnt
n := next (!n)
!cnt
Euler.Timer(p57)
val it : int * float = (153, 0.027241)
Starting with 1 and spiralling anticlockwise 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%?
open Euler
let p58() =
let rec loop total primes size =
let newPrimes =
[0..3] |> List.map(fun n -> size*size - n*(size-1))
|> List.filter Math.PrimeQ
|> List.length
|> (+) primes
let newTotal = total+4
let newSize = size+2
if newPrimes * 10 < newTotal then size
else loop newTotal newPrimes newSize
loop 1 0 3
Euler.Timer(p58)
val it : int * float = (26241, 4.9358527)
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.
open System
open Euler
let p59() =
let encrypted =
Euler.ReadDelimitedFile<string>(__SOURCE_DIRECTORY__ + "/txt/p059.txt",',')
|> Array.concat
|> Array.map byte
let isValidChar c =
let ch = char(c)
Char.IsLetterOrDigit(ch) || Char.IsPunctuation(ch) || Char.IsSeparator(ch)
let tryDecipher (key:byte[]) =
let decrypted = encrypted |> Array.mapi (fun i b -> b ^^^ key.[i%key.Length])
match decrypted |> Seq.forall isValidChar with
|true -> Some <| String(decrypted |> Array.map char)
|false -> None
let decrypted =
seq [ for a in 'a'..'z' do
for b in 'a'..'z' do
for c in 'a'..'z' ->
tryDecipher [| byte a; byte b; byte c |] ]
|> Seq.find (fun m -> m.IsSome)
|> fun m -> m.Value
decrypted |> Seq.sumBy (byte >> int)
Euler.Timer(p59)
val it : int * float = (107359, 0.1407496)
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.
open Euler
let p60() =
let concat a b = b + a * pown 10L (1+int(log10(float b)))
let testPair a b = Math.PrimeQ(concat a b) && Math.PrimeQ(concat b a)
// assuming answer will under 10000
let maxN = Math.PrimePi 10000
let init =
seq { for a in 4..maxN -> [Math.Prime a], a }
let next (prior:int64 list, a:int) =
seq { for b in a+1..maxN ->
(Math.Prime b)::prior, b }
|> Seq.filter (fun (s,_) -> s.Tail |> Seq.forall (testPair s.Head))
init
|> Seq.collect next // 2 primes
|> Seq.collect next // 3 primes
|> Seq.collect next // 4 primes
|> Seq.collect next // 5 primes
|> Seq.head
|> fst
|> Seq.sum
Euler.Timer(p60)
val it : int64 * float = (26033L, 39.809968)