Books I Like

Showing posts with label Clojure. Show all posts
Showing posts with label Clojure. Show all posts

Sunday, January 3, 2010

Solving Project Euler Problem #16 in Clojure

Problem Statement :

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2^1000?


Solution :
The easiest way to multiply a number by 2 is to perform a left bit shift.
Get the number, convert it to string, put the indices in a map and apply a "+" function on it.


(println (apply + (map #(Integer/parseInt (str %1)) (str (bit-shift-left 2 999)))))

Sunday, November 1, 2009

Solving Project Euler Problem #7 in Ruby, Clojure

Problem Statement :
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?

Solution :

This works on Ruby 1.9+. Here we have taken advantage of the method discusses here to create Lazy enumerator in Ruby. I started looking for the ruby equivalent as the clojure code becomes so easy to deal with using the lazy sequences.


require "mathn"
infinity = 1.0/0.0
module Enumerable
def lazy_select
Enumerator.new do |yielder|
each do |obj|
yielder.yield(obj) if yield(obj)
end
end
end
end

p (1..infinity).lazy_select { |v| v.prime? }.take(10001).last



The clojure code is as follows :
Here we have added one optimization (Any prime number after 2 and 3, when divided by 6, leaves the remainder 5 or 1).


(defn sqrt [x]
(int (Math/sqrt x)))

(defn get-smallest-prime-factor [n]
(loop [n n d 2]
(cond (> d (sqrt n)) n
(= n d) n
(= 0 (rem n d)) d
true (recur n (inc d)))))

(def get-nth-prime
(lazy-cat '(2 3)
(filter
#(= % (get-smallest-prime-factor %))
(filter
#(or (= 1 (rem % 6)) (= 5 (rem % 6)))
(take-nth 2 (iterate inc 3))))))

(println (nth get-nth-prime 10000))


Here is another cheat, if you have installed the clojure contrib library.


(use 'clojure.contrib.lazy-seqs)
(println (nth primes 10000))

Solving Project Euler Problem #6

Problem Statement :
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.

Solution is -> (n(n+1)/2)**2 - (n*(n+1)*(2n+1))/6



(defn euler6 [n] (- (* (/ (* n (+ n 1)) 2) (/ (* n (+ n 1)) 2)) (/ (* n (+ n 1) (+ 1 (* n 2))) 6)))
(println (euler6 100))

Get at Amazon