I got through the first 9 problems. The following are the solutions in Clojure. Each solution is contained within a box that you need to click to expose the code.
Keep in mind doing these problems has been a vehicle for me for exploring the Clojure language --- I'm sure to a Clojure guru, my code below is pretty crude.
I also apologize for the formatting of the code. My nice indenting was lost when I copied and pasted the code to my blog editor.
Enjoy!
Project Euler: Problem # 1
Show Code; If we list all the natural numbers below 10 that are multiples of 3 or 5, we
; get 3, 5, 6 and 9. The sum of these multiples is 23.
; Find the sum of all the multiples of 3 or 5 below 1000.
; This works - it uses your prototypical-style recursion. Unfortunately this
; implementation is not recommended as it is naturally stack consuming
; and will result in a stack-overflow error on large inputs.
(defn stack-consuming-SumMultiples [value mult_1 mult_2]
(let [ceilingVal (- value 1)]
(let [sum (if (or (= (rem ceilingVal mult_1) 0)
(= (rem ceilingVal mult_2) 0)) ceilingVal 0)]
(if (= ceilingVal 0) 0
(+ sum (SumMultiples ceilingVal mult_1 mult_2))))))
; This works and it is good that the recursive call was put
; into the tail position. Although Clojure will not do
; tail call optimization here, we've positioned ourself
; to use the 'recur' form.
(defn tail-SumMultiples [value mult_1 mult_2]
(letfn [(SumMults
[summ n]
(if (zero? n)
summ
(SumMults (+ summ (if (or (= (rem n mult_1) 0)
(= (rem n mult_2) 0)) n 0)) (dec n))))]
(SumMults 0 (dec value))))
; Using 'recur' - Clojure will do explicit tail call optimization (TCO)
(defn recur-SumMultiples [value mult_1 mult_2]
(letfn [(SumMults
[summ n]
(if (zero? n)
summ
(recur (+ summ (if (or (= (rem n mult_1) 0)
(= (rem n mult_2) 0)) n 0)) (dec n))))]
(SumMults 0 (dec value))))
; Using sequences! No recursion necessary using the sequence library
; that is part of Clojure.
(defn seq-SumMultiples [value mult_1 mult_2]
(reduce + (filter #(or (= (rem % mult_1) 0) (= (rem % mult_2) 0))
(range 1 value))))
; get 3, 5, 6 and 9. The sum of these multiples is 23.
; Find the sum of all the multiples of 3 or 5 below 1000.
; This works - it uses your prototypical-style recursion. Unfortunately this
; implementation is not recommended as it is naturally stack consuming
; and will result in a stack-overflow error on large inputs.
(defn stack-consuming-SumMultiples [value mult_1 mult_2]
(let [ceilingVal (- value 1)]
(let [sum (if (or (= (rem ceilingVal mult_1) 0)
(= (rem ceilingVal mult_2) 0)) ceilingVal 0)]
(if (= ceilingVal 0) 0
(+ sum (SumMultiples ceilingVal mult_1 mult_2))))))
; This works and it is good that the recursive call was put
; into the tail position. Although Clojure will not do
; tail call optimization here, we've positioned ourself
; to use the 'recur' form.
(defn tail-SumMultiples [value mult_1 mult_2]
(letfn [(SumMults
[summ n]
(if (zero? n)
summ
(SumMults (+ summ (if (or (= (rem n mult_1) 0)
(= (rem n mult_2) 0)) n 0)) (dec n))))]
(SumMults 0 (dec value))))
; Using 'recur' - Clojure will do explicit tail call optimization (TCO)
(defn recur-SumMultiples [value mult_1 mult_2]
(letfn [(SumMults
[summ n]
(if (zero? n)
summ
(recur (+ summ (if (or (= (rem n mult_1) 0)
(= (rem n mult_2) 0)) n 0)) (dec n))))]
(SumMults 0 (dec value))))
; Using sequences! No recursion necessary using the sequence library
; that is part of Clojure.
(defn seq-SumMultiples [value mult_1 mult_2]
(reduce + (filter #(or (= (rem % mult_1) 0) (= (rem % mult_2) 0))
(range 1 value))))
Project Euler: Problem # 2
Show Code; Each new term in the Fibonacci sequence is generated by adding the previous
; two terms. By starting with 1 and 2, the first 10 terms will be:
; 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
; By considering the terms in the Fibonacci sequence whose values do not
; exceed four million, find the sum of the even-valued terms.
; First we'll define a lazy sequence of Fibonacci numbers
(defn fibos []
(map first (iterate (fn[[a b]] [b (+ a b)]) [0 1])))
; Here we define the function that will do what we need...
(defn SumTerms [limit]
(reduce + (filter even? (take-while (fn[n] (<= n limit)) (fibos)))))
; two terms. By starting with 1 and 2, the first 10 terms will be:
; 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
; By considering the terms in the Fibonacci sequence whose values do not
; exceed four million, find the sum of the even-valued terms.
; First we'll define a lazy sequence of Fibonacci numbers
(defn fibos []
(map first (iterate (fn[[a b]] [b (+ a b)]) [0 1])))
; Here we define the function that will do what we need...
(defn SumTerms [limit]
(reduce + (filter even? (take-while (fn[n] (<= n limit)) (fibos)))))
Project Euler: Problem # 3
Show Code; The prime factors of 13195 are 5, 7, 13 and 29.
; What is the largest prime factor of the number 600851475143 ?
; Uses the 'trial division' method to check if input is a prime or not...
(use 'clojure.contrib.math)
(defn is-prime? [n]
(cond
(= n 1) false
(= n 2) true
(even? n) false
:else
(let [upperbound (+ (int (sqrt n)) 1)
factors (filter #(= (rem n %) 0) (range 3 upperbound 2))]
(empty? factors))))
; Finds the largest prime factor of supplied number...
(defn largest-prime-factor [n]
(let [upperbound (+ (int (sqrt n)) 1)
factors (filter #(= (rem n %) 0) (range 2 upperbound 1))
primeFactors (filter is-prime? factors)]
(last primeFactors)))
; What is the largest prime factor of the number 600851475143 ?
; Uses the 'trial division' method to check if input is a prime or not...
(use 'clojure.contrib.math)
(defn is-prime? [n]
(cond
(= n 1) false
(= n 2) true
(even? n) false
:else
(let [upperbound (+ (int (sqrt n)) 1)
factors (filter #(= (rem n %) 0) (range 3 upperbound 2))]
(empty? factors))))
; Finds the largest prime factor of supplied number...
(defn largest-prime-factor [n]
(let [upperbound (+ (int (sqrt n)) 1)
factors (filter #(= (rem n %) 0) (range 2 upperbound 1))
primeFactors (filter is-prime? factors)]
(last primeFactors)))
Project Euler: Problem # 4
Show Code; A palindromic number reads the same both ways. The largest palindrome made
; from the product of two 2-digit numbers is 9009 = 91 × 99.
; Find the largest palindrome made from the product of two 3-digit numbers.
; Okay, so I first defined this function to simply test if the first character
; and last character in the supplied string matched or not...
(defn outers-match? [nstr]
(if (= (first nstr) (last nstr)) true false))
; Then I defined this function that would strip the first and last character
; from the supplied string...
(defn drop-outers [nstr]
(apply str (drop-last (rest nstr))))
; So here's my own home-grown function for determining if the supplied
; number is a palindrome. It's recursive. I first compare the first
; and last characters; if they match they get stripped and I repeat. I
; guess it's a little clever, but WAAAY OVERLY COMPLICATED...
(defn is-palindrome-complicated? [n]
(loop [nstr (str n)]
(cond
(= 1 (count nstr)) true
(and
(= 2 (count nstr))
(outers-match? nstr)) true
:else
(if (outers-match? nstr)
(recur (drop-outers nstr)) false))))
; So here's the easy way to check if the supplied number is a palindrome.
; Convert the number to a string and compare it to a reverse of itself (duh)...
(defn is-palindrome-easy? [n]
(= (seq (str n)) (reverse (str n))))
; Returns a sequence of the product of 3-digit numbers; every permutation...
(defn all-products []
(for [i (range 100 1000) j (range 100 1000)] (* i j)))
; Solution to the problem...it simply uses the all-products function
; in conjunction with the is-palindrome? function to find our
; max...
(defn largest-palindrome []
(apply max (filter is-palindrome-easy? (all-products))))
; And...here's the solution all nice and neatly packed into a single 4-line
; function...
(defn largest-palindrome-compact []
(reduce max (for [x (range 100 1000) y (range 100 1000)
:when (= (str (* x y)) (apply str (reverse (str (* x y)))))]
(* x y))))
; from the product of two 2-digit numbers is 9009 = 91 × 99.
; Find the largest palindrome made from the product of two 3-digit numbers.
; Okay, so I first defined this function to simply test if the first character
; and last character in the supplied string matched or not...
(defn outers-match? [nstr]
(if (= (first nstr) (last nstr)) true false))
; Then I defined this function that would strip the first and last character
; from the supplied string...
(defn drop-outers [nstr]
(apply str (drop-last (rest nstr))))
; So here's my own home-grown function for determining if the supplied
; number is a palindrome. It's recursive. I first compare the first
; and last characters; if they match they get stripped and I repeat. I
; guess it's a little clever, but WAAAY OVERLY COMPLICATED...
(defn is-palindrome-complicated? [n]
(loop [nstr (str n)]
(cond
(= 1 (count nstr)) true
(and
(= 2 (count nstr))
(outers-match? nstr)) true
:else
(if (outers-match? nstr)
(recur (drop-outers nstr)) false))))
; So here's the easy way to check if the supplied number is a palindrome.
; Convert the number to a string and compare it to a reverse of itself (duh)...
(defn is-palindrome-easy? [n]
(= (seq (str n)) (reverse (str n))))
; Returns a sequence of the product of 3-digit numbers; every permutation...
(defn all-products []
(for [i (range 100 1000) j (range 100 1000)] (* i j)))
; Solution to the problem...it simply uses the all-products function
; in conjunction with the is-palindrome? function to find our
; max...
(defn largest-palindrome []
(apply max (filter is-palindrome-easy? (all-products))))
; And...here's the solution all nice and neatly packed into a single 4-line
; function...
(defn largest-palindrome-compact []
(reduce max (for [x (range 100 1000) y (range 100 1000)
:when (= (str (* x y)) (apply str (reverse (str (* x y)))))]
(* x y))))
Project Euler: Problem # 5
Show Code; 2520 is the smallest number that can be divided by each of the numbers from
; 1 to 10 without any remainder.
;
; What is the smallest positive number that is evenly divisible by all of the
; numbers from 1 to 20?
; Create a lazy sequence of the divisors...
(defn divisors [] (range 1 21))
; Returns true if the number n is evenly divisible by all the numbers in the
; supplied collection coll...
(defn all-divide-evenly? [n coll]
(every? #(= (rem n %) 0) coll))
; Starting from the value 2520, search, using recursion, the first value that
; is evenly divisible by all our divisors. This is a brute-force way of doing
; it...
(defn find-it []
(loop [n 2520]
(if (all-divide-evenly? n (divisors))
n
(recur (+ n 20)))))
; Okay, so the following functions are in support of solving this problem
; using a better algorithm...specifically the one documented on the
; Euler's answer PDF...
; First we have a predicate function that uses the 'trial division' method
; to check if input is a prime or not...
(use 'clojure.contrib.math)
(defn is-prime? [n]
(cond
(= n 1) false
(= n 2) true
(even? n) false
:else
(let [upperbound (+ (int (sqrt n)) 1)
factors (filter #(= (rem n %) 0) (range 3 upperbound 2))]
(empty? factors))))
; Lazily define the first n number of primes...
(defn primes [n]
(filter is-prime? (range 1 (inc n))))
; Function that returns the largest power such that base^x does not exceed n
; where 'x' is the value returned. For example,
; (get-greatest-perfect-power 2 20) will return 4, because 4 is the largest
; value such that 2^4 < 20...
(defn get-greatest-perfect-power [base n]
(loop [val 1
exp 1]
(if (> (* val base) n) (dec exp)
(recur (* val base) (inc exp)))))
; Returns the smallest value that is evenly divisible by all numbers 1-n. This
; solution is derived from the Euler answer PDF...
(defn find-it-optimized [n]
(reduce * (map #(expt % (get-greatest-perfect-power % n)) (primes n))))
; Some parting thoughts...turns out there are several ways in which you can
; compute the least common multiple (LCM):
; [http://en.wikipedia.org/wiki/Least_common_multiple#Computing_the_least_common_multiple]
; The method I used above is probably not the most efficient; the most
; expensive operation I believe is calculating the set of prime numbers. A
; better way to solve the problem is to use the "Euclidean algorithm" to
; compute the great common multiple of 2 numbers (a, b), and use that as the
; divisor to the value a*b. The result is the LCM.
; 1 to 10 without any remainder.
;
; What is the smallest positive number that is evenly divisible by all of the
; numbers from 1 to 20?
; Create a lazy sequence of the divisors...
(defn divisors [] (range 1 21))
; Returns true if the number n is evenly divisible by all the numbers in the
; supplied collection coll...
(defn all-divide-evenly? [n coll]
(every? #(= (rem n %) 0) coll))
; Starting from the value 2520, search, using recursion, the first value that
; is evenly divisible by all our divisors. This is a brute-force way of doing
; it...
(defn find-it []
(loop [n 2520]
(if (all-divide-evenly? n (divisors))
n
(recur (+ n 20)))))
; Okay, so the following functions are in support of solving this problem
; using a better algorithm...specifically the one documented on the
; Euler's answer PDF...
; First we have a predicate function that uses the 'trial division' method
; to check if input is a prime or not...
(use 'clojure.contrib.math)
(defn is-prime? [n]
(cond
(= n 1) false
(= n 2) true
(even? n) false
:else
(let [upperbound (+ (int (sqrt n)) 1)
factors (filter #(= (rem n %) 0) (range 3 upperbound 2))]
(empty? factors))))
; Lazily define the first n number of primes...
(defn primes [n]
(filter is-prime? (range 1 (inc n))))
; Function that returns the largest power such that base^x does not exceed n
; where 'x' is the value returned. For example,
; (get-greatest-perfect-power 2 20) will return 4, because 4 is the largest
; value such that 2^4 < 20...
(defn get-greatest-perfect-power [base n]
(loop [val 1
exp 1]
(if (> (* val base) n) (dec exp)
(recur (* val base) (inc exp)))))
; Returns the smallest value that is evenly divisible by all numbers 1-n. This
; solution is derived from the Euler answer PDF...
(defn find-it-optimized [n]
(reduce * (map #(expt % (get-greatest-perfect-power % n)) (primes n))))
; Some parting thoughts...turns out there are several ways in which you can
; compute the least common multiple (LCM):
; [http://en.wikipedia.org/wiki/Least_common_multiple#Computing_the_least_common_multiple]
; The method I used above is probably not the most efficient; the most
; expensive operation I believe is calculating the set of prime numbers. A
; better way to solve the problem is to use the "Euclidean algorithm" to
; compute the great common multiple of 2 numbers (a, b), and use that as the
; divisor to the value a*b. The result is the LCM.
Project Euler: Problem # 6
Show Code; The sum of the squares of the first ten natural numbers is,
; 1^2 + 2^2 + ... + 10^2 = 385
;
; The square of the sum of the first ten natural numbers is,
; (1 + 2 + ... + 10)^2 = 55^2 = 3025
;
; Hence the difference between the sum of the squares of the first ten natural
; numbers and the square of the sum is 3025 - 385 = 2640.
;
; Find the difference between the sum of the squares of the first one hundred
; natural numbers and the square of the sum.
; -------- BRUTE FORCE Implemenation -------------------
(defn sum-of-squares_bruteforce [n]
(reduce + (for [x (range (+ n 1))] (* x x))))
(defn square-of-sums_bruteforce [n]
(let [sum (reduce + (range (+ n 1)))]
(* sum sum)))
(defn find-difference_bruteforce [n]
(- (square-of-sums_bruteforce n) (sum-of-squares_bruteforce n)))
; ------------ Better (from Euler solution PDF) ------------
; see: http://en.wikipedia.org/wiki/Square_pyramidal_number
; ----------------------------------------------------------
(defn square-of-sums [n]
(let [sum (quot (* n (+ n 1)) 2)]
(* sum sum)))
(defn sum-of-squares [n]
(quot (* n (* (+ n 1) (+ (* 2 n) 1))) 6))
(defn find-difference [n]
(- (square-of-sums n) (sum-of-squares n)))
; 1^2 + 2^2 + ... + 10^2 = 385
;
; The square of the sum of the first ten natural numbers is,
; (1 + 2 + ... + 10)^2 = 55^2 = 3025
;
; Hence the difference between the sum of the squares of the first ten natural
; numbers and the square of the sum is 3025 - 385 = 2640.
;
; Find the difference between the sum of the squares of the first one hundred
; natural numbers and the square of the sum.
; -------- BRUTE FORCE Implemenation -------------------
(defn sum-of-squares_bruteforce [n]
(reduce + (for [x (range (+ n 1))] (* x x))))
(defn square-of-sums_bruteforce [n]
(let [sum (reduce + (range (+ n 1)))]
(* sum sum)))
(defn find-difference_bruteforce [n]
(- (square-of-sums_bruteforce n) (sum-of-squares_bruteforce n)))
; ------------ Better (from Euler solution PDF) ------------
; see: http://en.wikipedia.org/wiki/Square_pyramidal_number
; ----------------------------------------------------------
(defn square-of-sums [n]
(let [sum (quot (* n (+ n 1)) 2)]
(* sum sum)))
(defn sum-of-squares [n]
(quot (* n (* (+ n 1) (+ (* 2 n) 1))) 6))
(defn find-difference [n]
(- (square-of-sums n) (sum-of-squares n)))
Project Euler: Problem # 7
Show Code; By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
; What is the 10001st prime number?
; Uses the 'trial division' method to check if input is a prime or not
(use 'clojure.contrib.math)
(defn is-prime? [n]
(cond
(= n 1) false
(= n 2) true
(even? n) false
:else
(let [upperbound (+ (int (sqrt n)) 1)
factors (filter #(= (rem n %) 0) (range 3 upperbound 2))]
(empty? factors))))
; All prime numbers except for 2 are odd, so we'll create a lazy sequence of
; odd numbers...
(defn odd-numbers [] (iterate #(+ 2 %) 1))
; And here's the function that is our solution...
(defn nth-prime [n]
(nth (filter is-prime? (odd-numbers)) (- n 1)))
; What is the 10001st prime number?
; Uses the 'trial division' method to check if input is a prime or not
(use 'clojure.contrib.math)
(defn is-prime? [n]
(cond
(= n 1) false
(= n 2) true
(even? n) false
:else
(let [upperbound (+ (int (sqrt n)) 1)
factors (filter #(= (rem n %) 0) (range 3 upperbound 2))]
(empty? factors))))
; All prime numbers except for 2 are odd, so we'll create a lazy sequence of
; odd numbers...
(defn odd-numbers [] (iterate #(+ 2 %) 1))
; And here's the function that is our solution...
(defn nth-prime [n]
(nth (filter is-prime? (odd-numbers)) (- n 1)))
Project Euler: Problem # 8
Show Code; Find the greatest product of five consecutive digits in the 1000-digit number:
;
; 73167176531330624919225119674426574742355349194934
; 96983520312774506326239578318016984801869478851843
; 85861560789112949495459501737958331952853208805511
; 12540698747158523863050715693290963295227443043557
; 66896648950445244523161731856403098711121722383113
; 62229893423380308135336276614282806444486645238749
; 30358907296290491560440772390713810515859307960866
; 70172427121883998797908792274921901699720888093776
; 65727333001053367881220235421809751254540594752243
; 52584907711670556013604839586446706324415722155397
; 53697817977846174064955149290862569321978468622482
; 83972241375657056057490261407972968652414535100474
; 82166370484403199890008895243450658541227588666881
; 16427171479924442928230863465674813919123162824586
; 17866458359124566529476545682848912883142607690042
; 24219022671055626321111109370544217506941658960408
; 07198403850962455444362981230987879927244284909188
; 84580156166097919133875499200524063689912560717606
; 05886116467109405077541002256983155200055935729725
; 71636269561882670428252483600823257530420752963450
; Store the 1000-digit in a variable...
(def big-number 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450)
; Generic function that receives a string of digits and returns the product of them...
(defn get-product [nstr]
(reduce * (apply vector (map #(Integer/parseInt %) (map str (seq nstr))))))
; Generic function that receives a number and a chunkSize and returns a vector of
; the possible digit-strings...
(defn chunk-it-up [n chunkSize]
(let
[nstr (str n)
numDigits (count nstr)]
(loop [result [] cursor 0]
(if (> (+ cursor chunkSize) numDigits)
result
(recur (conj result (subs nstr cursor (+ cursor chunkSize))) (inc cursor))))))
; Finds the max-product of chunkSize consecutive digits in the supplied number n...
(defn find-max [n chunkSize]
(loop [
chunks (chunk-it-up n chunkSize)
maxVal (get-product (first chunks))]
(if (= (count chunks) 1)
maxVal
(recur (rest chunks) (max maxVal (get-product (second chunks)))))))
;
; 73167176531330624919225119674426574742355349194934
; 96983520312774506326239578318016984801869478851843
; 85861560789112949495459501737958331952853208805511
; 12540698747158523863050715693290963295227443043557
; 66896648950445244523161731856403098711121722383113
; 62229893423380308135336276614282806444486645238749
; 30358907296290491560440772390713810515859307960866
; 70172427121883998797908792274921901699720888093776
; 65727333001053367881220235421809751254540594752243
; 52584907711670556013604839586446706324415722155397
; 53697817977846174064955149290862569321978468622482
; 83972241375657056057490261407972968652414535100474
; 82166370484403199890008895243450658541227588666881
; 16427171479924442928230863465674813919123162824586
; 17866458359124566529476545682848912883142607690042
; 24219022671055626321111109370544217506941658960408
; 07198403850962455444362981230987879927244284909188
; 84580156166097919133875499200524063689912560717606
; 05886116467109405077541002256983155200055935729725
; 71636269561882670428252483600823257530420752963450
; Store the 1000-digit in a variable...
(def big-number 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450)
; Generic function that receives a string of digits and returns the product of them...
(defn get-product [nstr]
(reduce * (apply vector (map #(Integer/parseInt %) (map str (seq nstr))))))
; Generic function that receives a number and a chunkSize and returns a vector of
; the possible digit-strings...
(defn chunk-it-up [n chunkSize]
(let
[nstr (str n)
numDigits (count nstr)]
(loop [result [] cursor 0]
(if (> (+ cursor chunkSize) numDigits)
result
(recur (conj result (subs nstr cursor (+ cursor chunkSize))) (inc cursor))))))
; Finds the max-product of chunkSize consecutive digits in the supplied number n...
(defn find-max [n chunkSize]
(loop [
chunks (chunk-it-up n chunkSize)
maxVal (get-product (first chunks))]
(if (= (count chunks) 1)
maxVal
(recur (rest chunks) (max maxVal (get-product (second chunks)))))))
Project Euler: Problem # 9
Show Code; A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
; a2 + b2 = c2
;
; For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2
;
; There exists exactly one Pythagorean triplet for which a + b + c = 1000.
; Find the product abc.
(use 'clojure.contrib.math)
; So this is just my little version of a function that calculates the
; greatest-common divisor of 2 numbers. This is Euclid's Algorithm
; (http://en.wikipedia.org/wiki/Euclid%27s_algorithm).
(defn paul_gcd [a b]
(if (= (mod a b) 0) b
(recur b (mod a b))))
; This function calculates a Pythagorean Triplet using the "Two-Fractions"
; method (http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Pythag/pythag.html#twofractions).
; I choose to use this method as it GUARANTEES to generate every possible
; Pythagorean Triplet (unlike other algorithms for generating triplets).
; The output of this function is a vector [a, b, c] which is the triplet.
; When using the "Two-Fractions" method, the right-hand fraction (2b / a)
; is brought to its "lowest form" using the 'paul_gcd' function.
(defn pythagorean-triplet-lowestform [k a b]
(let [
F1Numerator (* k a)
F1Denominator (* k b)
F2Numerator (* 2 b)
F2Denominator a
F1Numerator_plus2 (+ F1Numerator (* 2 F1Denominator))
F2Numerator_plus2 (+ F2Numerator (* 2 F2Denominator))
F2Divisor (paul_gcd F2Numerator_plus2 F2Denominator)
F2Numerator_lowestForm (quot F2Numerator_plus2 F2Divisor)
F2Denominator_lowestForm (quot F2Denominator F2Divisor)
leg1 (* F1Numerator_plus2 F2Denominator_lowestForm)
leg2 (* F2Numerator_lowestForm F1Denominator)
leg3 (sqrt (+ (* leg1 leg1) (* leg2 leg2)))]
(vector leg1 leg2 leg3)))
; This function returns the first a-b vector in which the Pythagorean Triplet
; generated from it (using the "Two-Fractions" method) matches 'n'. If there
; is no triplet whose sum equals 'n', nil is returned.
(defn first-ab-vector-with-matching-triplet-sum [n]
(loop [
loopVar 1]
(let [
abVec (first (filter #(not (nil? %)) (for [a (range 1 loopVar) b (range 1 loopVar)] (if (= n (reduce + (pythagorean-triplet-lowestform 1 a b))) [a b] nil))))]
(if (> loopVar n) nil
(if (not (nil? abVec)) abVec
(recur (inc loopVar)))))))
; This function will return the product of the Pythagorean Triplet whose sum
; matches 'n'. If there is no triplet whose sum matches 'n', nil is
; returned.
(defn get-product-of-pythagorean-triplet-whose-sum-is [n]
(let [
abVec (first-ab-vector-with-matching-triplet-sum n)]
(if (not (nil? abVec)) (reduce * (pythagorean-triplet-lowestform 1 (first abVec) (second abVec))) nil)))
(use 'clojure.contrib.math)
; So this is just my little version of a function that calculates the
; greatest-common divisor of 2 numbers. This is Euclid's Algorithm
; (http://en.wikipedia.org/wiki/Euclid%27s_algorithm).
(defn paul_gcd [a b]
(if (= (mod a b) 0) b
(recur b (mod a b))))
; This function calculates a Pythagorean Triplet using the "Two-Fractions"
; method (http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Pythag/pythag.html#twofractions).
; I choose to use this method as it GUARANTEES to generate every possible
; Pythagorean Triplet (unlike other algorithms for generating triplets).
; The output of this function is a vector [a, b, c] which is the triplet.
; When using the "Two-Fractions" method, the right-hand fraction (2b / a)
; is brought to its "lowest form" using the 'paul_gcd' function.
(defn pythagorean-triplet-lowestform [k a b]
(let [
F1Numerator (* k a)
F1Denominator (* k b)
F2Numerator (* 2 b)
F2Denominator a
F1Numerator_plus2 (+ F1Numerator (* 2 F1Denominator))
F2Numerator_plus2 (+ F2Numerator (* 2 F2Denominator))
F2Divisor (paul_gcd F2Numerator_plus2 F2Denominator)
F2Numerator_lowestForm (quot F2Numerator_plus2 F2Divisor)
F2Denominator_lowestForm (quot F2Denominator F2Divisor)
leg1 (* F1Numerator_plus2 F2Denominator_lowestForm)
leg2 (* F2Numerator_lowestForm F1Denominator)
leg3 (sqrt (+ (* leg1 leg1) (* leg2 leg2)))]
(vector leg1 leg2 leg3)))
; This function returns the first a-b vector in which the Pythagorean Triplet
; generated from it (using the "Two-Fractions" method) matches 'n'. If there
; is no triplet whose sum equals 'n', nil is returned.
(defn first-ab-vector-with-matching-triplet-sum [n]
(loop [
loopVar 1]
(let [
abVec (first (filter #(not (nil? %)) (for [a (range 1 loopVar) b (range 1 loopVar)] (if (= n (reduce + (pythagorean-triplet-lowestform 1 a b))) [a b] nil))))]
(if (> loopVar n) nil
(if (not (nil? abVec)) abVec
(recur (inc loopVar)))))))
; This function will return the product of the Pythagorean Triplet whose sum
; matches 'n'. If there is no triplet whose sum matches 'n', nil is
; returned.
(defn get-product-of-pythagorean-triplet-whose-sum-is [n]
(let [
abVec (first-ab-vector-with-matching-triplet-sum n)]
(if (not (nil? abVec)) (reduce * (pythagorean-triplet-lowestform 1 (first abVec) (second abVec))) nil)))