November 30, 2008
at
Sunday, November 30, 2008
Labels:
Computer Science,
Lisp,
Project Euler
Posted by
Billy
1 comments
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
Common Lisp handles big numbers for you, so this problem is very easy.
(defparameter numbers '(
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690 ))
(defun euler-13 ()
(subseq (write-to-string (apply #'+ numbers))
0 10))
November 29, 2008
at
Saturday, November 29, 2008
Labels:
Computer Science,
Lisp,
Project Euler
Posted by
Billy
0
comments
What is the greatest product of four adjacent numbers in any direction (up, down, left, right, or diagonally) in the 2020 grid?
This solution scans four rows at a time, saves the max adjacent product and scans the next four rows.
(defparameter *grid*
'((08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08)
(49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00)
(81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65)
(52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91)
(22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80)
(24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50)
(32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70)
(67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21)
(24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72)
(21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95)
(78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92)
(16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57)
(86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58)
(19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40)
(04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66)
(88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69)
(04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36)
(20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16)
(20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54)
(01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48)))
(defun max-r (grid)
"Returns the maximum product of each rows elements"
(apply #'max (mapcar #'(lambda (lst) (apply #'* lst))
grid)))
(defun max-c (grid)
"Returns the maximum product of each columns elements"
;; Transpose the grid then call max-r
(max-r (apply #'mapcar #'list grid)))
(defun diag-prod (grid &optional (accum 1))
"Returns the product of the grids diagonal elements,
starting from the top left to the bottom right.
The function works recursively. If there is a top-left
element in the grid, it multiplies accum by the element.
Then it calls itself with the top row and first column
of the grid removed"
(if grid
(diag-prod (mapcar #'cdr (cdr grid)) (* accum (caar grid)))
accum))
(defun max-d (grid)
"Returns the maximum product of each diagonals elements"
(max (diag-prod grid)
(diag-prod (mapcar #'reverse grid))))
(defun max-adj (grid)
"Returns the maximum product of the grids adjacent elements.
Elements are multiplied in rows, columns, and diagonals"
(max (max-r grid) (max-c grid) (max-d grid)))
(defun max-in-4byX (grid &optional (result 0))
"Returns the maximum product of 4 adjacent elements in
a grid with 4 rows and a variable number of columns"
(if (< (length (car grid)) 4)
result
(let* ((subgrid (mapcar #'(lambda (lst)
(subseq lst 0 4))
grid))
(max-in-subgrid (max-adj subgrid))
(cur-result (cond ((< result max-in-subgrid) max-in-subgrid)
(t result))))
(max-in-4byX (mapcar #'cdr grid) cur-result))))
(defun euler-11 (grid &optional (result 0))
"Calculates the max prod of 4 adjacent elements in the top 4 rows
of a grid, removes the top row and repeats. Returns the maximum
product of 4 adjacent numbers in the entire grid"
(if (< (length grid) 4)
result
(let* ((top-4-rows (subseq grid 0 4))
(max-in-top-4 (max-in-4byX top-4-rows))
(cur-result (cond ((< result max-in-top-4) max-in-top-4)
(t result))))
(euler-11 (cdr grid) cur-result))))
at
Saturday, November 29, 2008
Labels:
Computer Science,
Lisp,
Project Euler
Posted by
Billy
0
comments
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.
This solution tests if a number is prime by testing if the number's smallest divisor is equal to itself. It then loops through all the odd numbers by two and sums the primes.
;;; Functions for testing if a number is prime
(defun square (x) (* x x))
(defun dividesp (a b)
(zerop (mod b a)))
(defun find-divisor (n test-divisor)
(cond ((> (square test-divisor) n) n)
((dividesp test-divisor n) test-divisor)
(t (find-divisor n (+ test-divisor 1)))))
(defun smallest-divisor (n)
(find-divisor n 2))
(defun primep (n)
(= n (smallest-divisor n)))
;;; End of prime functions
(defun sum-of-primes-below (num)
"Returns the sum of all the prime numbers below num"
(+ 2 (loop for i from 3 to num by 2 when (primep i) sum i)))
(defun euler-10 ()
(sum-of-primes-below 2000000))
at
Saturday, November 29, 2008
Labels:
Computer Science,
Lisp,
Project Euler
Posted by
Billy
0
comments
A Pythagorean triplet is a set of three natural numbers, a b c, for which a2 + b2 = c2.
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
A brute-force solution in Common Lisp:
(defun sqrd (x)
(* x x))
(defun pythag-trip-p (a b c)
"Tests if a b and c satisfies the pythagorean equation"
(eq (sqrd c)
(+ (sqrd a) (sqrd b))))
(defun sum-eq-1000-p (a b c)
"Tests if the sum equals 100"
(= 1000 (+ a b c)))
(defun euler-9 ()
(let ((result nil))
(loop for a from 1 to 1000 until (not (null result)) do
(loop for b from 1 to 1000 until (not (null result)) do
(let ((c (sqrt (+ (sqrd a) (sqrd b)))))
(when (sum-eq-1000-p a b c)
(print (list a b c))
(setf result (list a b c))))))
(apply #'* result)))
at
Saturday, November 29, 2008
Labels:
Computer Science,
Lisp,
Project Euler
Posted by
Billy
0
comments
Find the greatest product of five consecutive digits in the 1000-digit number.
;;; Use emacs to paste and format the 1000 digit number
(defvar long-number '(
7 3 1 6 7 1 7 6 5 3 1 3 3 0 6 2 4 9 1 9 2 2 5 1 1 9 6 7 4 4 2 6 5 7 4
7 4 2 3 5 5 3 4 9 1 9 4 9 3 4 9 6 9 8 3 5 2 0 3 1 2 7 7 4 5 0 6 3 2 6
2 3 9 5 7 8 3 1 8 0 1 6 9 8 4 8 0 1 8 6 9 4 7 8 8 5 1 8 4 3 8 5 8 6 1
5 6 0 7 8 9 1 1 2 9 4 9 4 9 5 4 5 9 5 0 1 7 3 7 9 5 8 3 3 1 9 5 2 8 5
3 2 0 8 8 0 5 5 1 1 1 2 5 4 0 6 9 8 7 4 7 1 5 8 5 2 3 8 6 3 0 5 0 7 1
5 6 9 3 2 9 0 9 6 3 2 9 5 2 2 7 4 4 3 0 4 3 5 5 7 6 6 8 9 6 6 4 8 9 5
0 4 4 5 2 4 4 5 2 3 1 6 1 7 3 1 8 5 6 4 0 3 0 9 8 7 1 1 1 2 1 7 2 2 3
8 3 1 1 3 6 2 2 2 9 8 9 3 4 2 3 3 8 0 3 0 8 1 3 5 3 3 6 2 7 6 6 1 4 2
8 2 8 0 6 4 4 4 4 8 6 6 4 5 2 3 8 7 4 9 3 0 3 5 8 9 0 7 2 9 6 2 9 0 4
9 1 5 6 0 4 4 0 7 7 2 3 9 0 7 1 3 8 1 0 5 1 5 8 5 9 3 0 7 9 6 0 8 6 6
7 0 1 7 2 4 2 7 1 2 1 8 8 3 9 9 8 7 9 7 9 0 8 7 9 2 2 7 4 9 2 1 9 0 1
6 9 9 7 2 0 8 8 8 0 9 3 7 7 6 6 5 7 2 7 3 3 3 0 0 1 0 5 3 3 6 7 8 8 1
2 2 0 2 3 5 4 2 1 8 0 9 7 5 1 2 5 4 5 4 0 5 9 4 7 5 2 2 4 3 5 2 5 8 4
9 0 7 7 1 1 6 7 0 5 5 6 0 1 3 6 0 4 8 3 9 5 8 6 4 4 6 7 0 6 3 2 4 4 1
5 7 2 2 1 5 5 3 9 7 5 3 6 9 7 8 1 7 9 7 7 8 4 6 1 7 4 0 6 4 9 5 5 1 4
9 2 9 0 8 6 2 5 6 9 3 2 1 9 7 8 4 6 8 6 2 2 4 8 2 8 3 9 7 2 2 4 1 3 7
5 6 5 7 0 5 6 0 5 7 4 9 0 2 6 1 4 0 7 9 7 2 9 6 8 6 5 2 4 1 4 5 3 5 1
0 0 4 7 4 8 2 1 6 6 3 7 0 4 8 4 4 0 3 1 9 9 8 9 0 0 0 8 8 9 5 2 4 3 4
5 0 6 5 8 5 4 1 2 2 7 5 8 8 6 6 6 8 8 1 1 6 4 2 7 1 7 1 4 7 9 9 2 4 4
4 2 9 2 8 2 3 0 8 6 3 4 6 5 6 7 4 8 1 3 9 1 9 1 2 3 1 6 2 8 2 4 5 8 6
1 7 8 6 6 4 5 8 3 5 9 1 2 4 5 6 6 5 2 9 4 7 6 5 4 5 6 8 2 8 4 8 9 1 2
8 8 3 1 4 2 6 0 7 6 9 0 0 4 2 2 4 2 1 9 0 2 2 6 7 1 0 5 5 6 2 6 3 2 1
1 1 1 1 0 9 3 7 0 5 4 4 2 1 7 5 0 6 9 4 1 6 5 8 9 6 0 4 0 8 0 7 1 9 8
4 0 3 8 5 0 9 6 2 4 5 5 4 4 4 3 6 2 9 8 1 2 3 0 9 8 7 8 7 9 9 2 7 2 4
4 2 8 4 9 0 9 1 8 8 8 4 5 8 0 1 5 6 1 6 6 0 9 7 9 1 9 1 3 3 8 7 5 4 9
9 2 0 0 5 2 4 0 6 3 6 8 9 9 1 2 5 6 0 7 1 7 6 0 6 0 5 8 8 6 1 1 6 4 6
7 1 0 9 4 0 5 0 7 7 5 4 1 0 0 2 2 5 6 9 8 3 1 5 5 2 0 0 0 5 5 9 3 5 7
2 9 7 2 5 7 1 6 3 6 2 6 9 5 6 1 8 8 2 6 7 0 4 2 8 2 5 2 4 8 3 6 0 0 8
2 3 2 5 7 5 3 0 4 2 0 7 5 2 9 6 3 4 5 0))
(defun euler-8 (num &optional (current-max 0))
"Returns the greatest product of five consecutive digits in the
given number. The digits must be supplied as a list"
(if (< (length num) 5)
current-max
(let ((product (apply #'* (subseq num 0 5))))
(if (> product current-max)
(euler-8 (cdr num) product)
(euler-8 (cdr num) current-max)))))
at
Saturday, November 29, 2008
Labels:
Computer Science,
Lisp,
SICP
Posted by
Billy
0
comments
SICP Exerice 1.29
Simpson's Rule is a more accurate method of numerical integration than the method illustrated above. Using Simpson's Rule, the integral of a function f between a and b is approximated as
(h/3)(y0 + 4y1 + 2y2 + 4y3 + 2y4 + ...+ 2yn-2 + 4yn-4 + yn)
where h = (b - a)/n, for some even integer n, and yk = f(a + kh). (Increasing n increases the accuracy of the approximation.) Define a procedure that takes as arguments f, a, b, and n and returns the value of the integral, computed using Simpson's Rule. Use your procedure to integrate cube between 0 and 1 (with n = 100 and n = 1000), and compare the results to those of the integral procedure shown above.
(defun cube (x) (* x x x))
(defun sum (term a next b)
(if (> a b)
0
(+ (funcall term a)
(sum term (funcall next a) next b))))
(defun integral (f a b n)
(let ((h (/ (- b a) n)))
(labels ((yk (k)
(funcall f (+ a (* k h))))
(inc2 (n) (+ n 2)))
(* (/ h 3)
(+ (yk 0)
(* 4 (sum #'yk 1 #'inc2 (- n 1)))
(* 2 (sum #'yk 2 #'inc2 (- n 2)))
(yk n))))))
SICP Exercise 1.30
The sum procedure above generates a linear recursion. The procedure can be rewritten so that the sum is performed iteratively. Show how to do this by filling in the missing expressions in the following definition:
(define (sum term a next b)
(define (iter a result)
(if <??>
<??>
(iter <??> <??>)))
(iter <??> <??>))
(defun new-sum (term a next b)
(labels ((iter (a result)
(if (> a b)
result
(iter (funcall next a)
(+ result (funcall term a))))))
(iter a 0)))
(defun inc (x) (+ x 1))
SICP Exercise 1.31
a. The sum procedure is only the simplest of a vast number of similar abstractions that can be captured as higher-order procedures.51 Write an analogous procedure called product that returns the product of the values of a function at points over a given range. Show how to define factorial in terms of product. Also use product to compute approximations to using the formula
(pie/4)=((2/3)(4/3)(4/5)(6/5)(6/7)(8/7)...)
b. If your product procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.
(defun product (term a next b)
(if (> a b)
1
(* (funcall term a)
(product term (funcall next a) next b))))
(defun new-product (term a next b)
(labels ((iter (a result)
(if (> a b)
result
(iter (funcall next a) (* result (funcall term a))))))
(iter a 1)))
(defun factorial (n)
(labels ((ident (x) x))
(product #'ident 1 #'inc n)))
(defun my-pie (n)
(labels ((num-term (n)
(if (oddp n)
(- n 1)
n))
(den-term (n)
(if (evenp n)
(- n 1)
n)))
(float(* 4
(/ (product #'num-term 3 #'inc n)
(product #'den-term 3 #'inc n))))))
SICP Exercise 1.32
a. Show that sum and product (exercise 1.31) are both special cases of a still more general notion called accumulate that combines a collection of terms, using some general accumulation function:
(accumulate combiner null-value term a next b)
Accumulate takes as arguments the same term and range specifications as sum and product, together with a combiner procedure (of two arguments) that specifies how the current term is to be combined with the accumulation of the preceding terms and a null-value that specifies what base value to use when the terms run out. Write accumulate and show how sum and product can both be defined as simple calls to accumulate.
b. If your accumulate procedure generates a recursive process,write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.
(defun accumulate (combiner null-value term a next b)
(if (> a b)
null-value
(funcall combiner (funcall term a)
(accumulate combiner null-value term
(funcall next a)
next b))))
(defun new-accumulate (combiner null-value term a next b)
(labels ((iter (a result)
(if (> a b)
result
(iter (funcall next a)
(funcall combiner result (funcall term a))))))
(iter a null-value)))
SICP Exercise 1.33
You can obtain an even more general version of accumulate (exercise 1.32) by introducing the notion of a filter on the terms to be combined. That is, combine only those terms derived from values in the range that satisfy a specified condition. The resulting filtered-accumulate abstraction takes the same arguments as accumulate, together with an additional predicate of one argument that specifies the filter. Write filtered-accumulate as a procedure. Show how to express the following using filtered-accumulate:
a. the sum of the squares of the prime numbers in the interval a to b (assuming that you have a prime? predicate already written)
b. the product of all the positive integers less than n that arerelatively prime to n (i.e., all positive integers i < n suchthat GCD(i,n) = 1).
(defun accumulate-if (filter combiner null-value term a next b)
(cond ((> a b) null-value)
((funcall filter a)
(funcall combiner
(funcall term a)
(accumulate-if filter
combiner
null-value
term
(funcall next a)
next
b)))
(t (accumulate-if filter
combiner
null-value
term
(funcall next a)
next
b))))
(defun prime-squared-sum (a b)
(accumulate-if 'primep
'+
0
#'(lambda(x) (* x x))
a
'inc
b))
(defun rel-prime-product (n)
(labels ((rel-prime-p (x)
(if (= 1 (gcd x n))
t)))
(accumulate-if #'rel-prime-p
'*
1
#'(lambda(x) x)
1
'inc
(- n 1))))
SICP Exercise 1.35
Show that the golden ratio (section 1.2.2) is a fixed point of the transformation x - 1 + 1/x, and use this fact to compute GO by means of the fixed-point procedure.
(defconstant +tolerance+ .00001)
(defun fixed-point (f first-guess)
(labels ((close-enough-p (v1 v2)
(< (abs (- v1 v2)) +tolerance+))
(try (guess)
(let ((next (funcall f guess)))
(if (close-enough-p guess next)
next
(try next)))))
(try first-guess)))
SICP Exercise 1.36
Modify fixed-point so that it prints the sequence of approximations it generates, using the newline and display primitives shown in exercise 1.22. Then find a solution to xx = 1000 by finding a fixed point of x log(1000)/log(x). (Use Scheme's primitive log procedure, which computes natural logarithms.) Compare the number of steps this takes with and without average damping. (Note that you cannot start fixed-point with a guess of 1, as this would cause division by log(1) =
0.)
(defun fixed-point-print (f first-guess)
(labels ((close-enough-p (v1 v2)
(< (abs (- v1 v2)) +tolerance+))
(try (guess)
(print guess)
(let ((next (funcall f guess)))
(if (close-enough-p guess next)
next
(try next)))))
(try first-guess)))
SICP Exercise 1.37
a. An infinite continued fraction is an expression of the form
f = N1/(D1+(N2/(D2+(N3/(D3+...
As an example, one can show that the infinite continued fraction expansion with the Ni and the Di all equal to 1 produces 1/phi , where phi is the golden ratio (described in section 1.2.2). One way to approximate an infinite continued fraction is to truncate the expansion after a given number of terms. Such a truncation -- a so-called k-term finite continued fraction -- has the form
N1/(D1+(N2/(...+Nk/Dk)
Suppose that n and d are procedures of one argument (the term index i) that return the Ni and Di of the terms of the continued fraction. Define a procedure cont-frac such that evaluating (cont-frac n d k) computes the value of the k-term finite continued fraction. Check your procedure by approximating1/phi using
(cont-frac (lambda (i) 1.0)
(lambda (i) 1.0)
k)
for successive values of k. How large must you make k in order to get an approximation that is accurate to 4 decimal places?b. If your cont-frac procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.
(defun cont-frac (n d k &optional (i 1))
(if (> i k)
0
(/ (funcall n i)
(+ (funcall d i) (cont-frac n d k (+ i 1))))))
(defun cont-frac-iter (n d k &optional (i k) (result 0))
(if (< i 1)
result
(cont-frac-iter n d k
(- i 1)
(/ (funcall n i)
(+ (funcall d i) result)))))
SICP Exercise 1.38
In 1737, the Swiss mathematician Leonhard Euler published a memoir De Fractionibus Continuis, which included a continued fraction expansion for e - 2, where e is the base of the natural logarithms. In this fraction, the Ni are all 1, and the Di are successively 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, .... Write a program that uses your cont-frac procedure from exercise 1.37 to approximate e, based on Euler's expansion.
(defun d (i)
"The D function to pass to cont-frac"
(cond ((= i 2) 2)
((zerop (mod (+ 1 i) 3)) (- i (/ i 3)))
(t 1)))
SICP Exercise 1.39
A continued fraction representation of the tangent function was published in 1770 by the German mathematician J.H. Lambert:
tan r = r/(1-(r^2/(3-(r^2/5-....
where x is in radians. Define a procedure (tan-cf x k) that computes an approximation to the tangent function based on Lambert's formula. K specifies the number of terms to compute, as in exercise 1.37.
(defun tan-cf (x k)
(labels ((tan-n (i)
(if (= i 1)
x
(- (* x x))))
(tan-d (i)
(if (= i 1)
1
(- (* 2 i)
1))))
(cont-frac #'tan-n #'tan-d k)))
SICP Exercise 1.40
Define a procedure cubic that can be used together with the
newtons-method procedure in expressions of the form (newtons-method
(cubic a b c) 1) to approximate zeros of the cubic x3 + ax2 + bx + c.
;;; Scheme functions redefined in CL
(defconstant +tolerance+ 0.00001)
(defconstant +dx+ 0.00001)
(defun deriv (g)
(lambda (x)
(/ (- (funcall g (+ x +dx+)) (funcall g x))
+dx+)))
(defun newton-transform (g)
(lambda (x)
(- x (/ (funcall g x) (funcall (deriv g) x)))))
(defun newton-method (g guess)
(fixed-point (newton-transform g) guess))
;;; Cubic function
(defun cubic (a b c)
(lambda (x)
(+ (* x x x)
(* a x x)
(* b x)
c)))
SICP Exercise 1.41
Define a procedure double that takes a procedure of one argumentasargument and returns a procedure that applies the original proceduretwice. For example, if inc is a procedure that adds1 to its argument,then (double inc) should be a procedure that adds 2. What value is returned by (((double (double double)) inc) 5)
(defun double (procedure)
(lambda (x)
(funcall procedure (funcall procedure x))))
SICP Exercise 1.42
Let f and g be two one-argument functions. The composition f afterg is defined to be the function x f(g(x)). Define a procedure compose that implements composition. For example, if inc is a procedure that adds 1 to its argument,((compose square inc) 6) 49
(defun compose (f g)
(lambda (x)
(funcall f (funcall g x))))
SICP Exercise 1.43
If f is a numerical function and n is a positive integer, then we can form the nth repeated application of f, which is defined to be the function whose value at x is f(f(...(f(x))...)). For example, if f is the function x x + 1, then the nth repeated application of f is the function x x + n. If f is the operation of squaring a number, then the nth repeated application of f is the function that raises its argument to the 2nth power. Write a procedure that takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f. Your procedure should be able to be used as follows:
((repeated square 2) 5)
625
(defun repeated (f n &optional (count 1))
(if (>= count n)
(lambda (x) (funcall f x))
(compose (repeated f n (+ count 1)) f)))
SICP Exercise 1.44
The idea of smoothing a function is an important concept in signal processing. If f is a function and dx is some small number, then the smoothed version of f is the function whose value at a point x is the average of f(x - dx), f(x), and f(x + dx). Write a procedure smooth that takes as input a procedure that computes f and returns a procedure that computes the smoothed f. It is sometimes valuable to repeatedly smooth a function (that is, smooth the smoothed function, and so on) to obtained the n-fold smoothed function. Show how to generate the n-fold smoothed function of any given function using smooth and repeated from exercise 1.43.
(defun smoothed (f)
(lambda (x)
(/ (+ (funcall f (- x +dx+))
(funcall f x)
(funcall f (+ x +dx+)))
3)))
(defun n-fold-smoothed (f n)
(repeated (smoothed f) n))
SICP Exercise 1.45
We saw in section 1.3.3 that attempting to compute square roots by naively finding a fixed point of y x/y does not converge, and that this can be fixed by average damping. The same method works for finding cube roots as fixed points of the average-damped y x/y2. Unfortunately, the process does not work for fourth roots -- a single average damp is not enough to make a fixed-point search for y x/y3 converge. On the other hand, if we average damp twice (i.e., use the average damp of the average damp of y x/y3) the fixed-point search does converge. Do some experiments to determine how many average damps are required to compute nth roots as a fixed-point search based upon repeated average damping of y x/yn-1. Use this to implement a simple procedure for computing nth roots using fixedpoint, average-damp, and the repeated procedure of exercise 1.43. Assume that any arithmetic operations you need are available as primitives.
;;; Scheme functions redefined in CL
(defun average-damp (f)
(lambda (x) (/ (+ x (funcall f x))
2)))
;;; End scheme functions
(defun nth-root (x n times)
(fixed-point (repeated (average-damp (lambda (y)
(/ (+ y
(/ x (expt y (- n 1))))
2)))
times)
1.0))
SICP Exercise 1.46
Several of the numerical methods described in this chapter are instances of an extremely general computational strategy known as iterative improvement. Iterative improvement says that, to compute something, we start with an initial guess for the answer, test if the guess is good enough, and otherwise improve the guess and continue the process using the improved guess as the new guess. Write a procedure iterative-improve that takes two procedures as arguments: a method for telling whether a guess is good enough and a method for improving a guess. Iterative-improve should return as its value a procedure that takes a guess as argument and keeps improving the guess until it is good enough. Rewrite the sqrt procedure of section 1.1.7 and the fixed-point procedure of section 1.3.3 in terms of iterative-improve.
(defun iterative-improve (good-enough-p improve)
(lambda (x)
(labels ((next-guess (guess)
(let ((improved-guess (funcall improve guess)))
(if (funcall good-enough-p guess improved-guess)
improved-guess
(next-guess improved-guess)))))
(next-guess x))))
(defun sqrt-improve (x)
(funcall (iterative-improve (lambda (guess z)
(let ((ratio (/ guess z)))
(and (< ratio 1.001) (> ratio 0.999))))
(lambda (guess)
(/ (+ guess (/ x guess))
2)))
1.0))
November 23, 2008
at
Sunday, November 23, 2008
Labels:
Computer Science,
Lisp,
SICP
Posted by
Billy
0
comments
SICP Exercise 1.11
A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.
(defun f (n)
"Recursive"
(cond ((< n 3) n)
(t (+ (f (- n 1))
(* 2 (f (- n 2)))
(* 3 (f (- n 3)))))))
(defun f2 (n)
"Iterative"
(if (< n 3)
n
(f2-iter n 2 1 0)))
(defun f2-iter (count &optional fn-1 fn-2 fn-3)
(if (< count 3)
fn-1
(progn (psetf fn-1 (+ fn-1 (* 2 fn-2) (* 3 fn-3))
fn-2 fn-1
fn-3 fn-2)
(f2-iter (- count 1) fn-1 fn-2 fn-3))))
SICP Exercise 1.12
Write a procedure that computes elements of Pascal's triangle by means of a recursive process.
(defun gen-row (lst)
"Given a list of values of the above row in Pascal's triangle,
generates the values in the current row except for the leading and
trailing 1"
(when (> (length lst) 1)
(cons (+ (first lst) (second lst)) (gen-row (cdr lst)))))
(defun pascal (row)
"Returns the values in the given row number of Pascal;s triangle"
(if (eq row 1)
'(1)
(append '(1) (gen-row (pascal (- row 1))) '(1))))
SICP Exercise 1.16
Design a procedure that evolves an iterative exponentiation process that uses successive squaring and uses a logarithmic number of steps, as does fast-expt. (Hint: Using the observation that (bn/2)2 = (b2)n/2, keep, along with the exponent n and the base b, an additional state variable a, and define the state transformation in such a way that the product a bn is unchanged from state to state. At the beginning of the process a is taken to be 1, and the answer is given by the value of a at the end of the process. In general, the technique of defining an invariant quantity that remains unchanged from state to state is a powerful way to think about the design of iterative algorithms.)
(defun my-expt (b n &optional (result 1))
(cond ((zerop n) result)
((evenp n) (my-expt (* b b) (/ n 2) result))
(t (my-expt b (- n 1) (* b result)))))
SICP Exercise 1.17
The exponentiation algorithms in this section are based on performing exponentiation by means of repeated multiplication. In a similar way, one can perform integer multiplication by means of repeated addition. The following multiplication procedure (in which it is assumed that our language can only add, not multiply) is analogous to the expt procedure:
(define (* a b)
(if (= b 0)
0
(+ a (* a (- b 1)))))
This algorithm takes a number of steps that is linear in b. Now suppose we include, together with addition, operations double, which doubles an integer, and halve, which divides an (even) integer by 2. Using these, design a multiplication procedure analogous to fast-expt that uses a logarithmic number of steps.
(defun double (x) (+ x x))
(defun half (x) (/ x 2))
(defun fast-mult (a b)
(cond ((zerop b) 0)
((evenp b) (double (fast-mult a (half b))))
(t (+ a (fast-mult a (- b 1))))))
SICP Exercise 1.18
Using the results of exercises 1.16 and 1.17, devise a procedure that generates an iterative process for multiplying two integers in terms of adding, doubling, and halving and uses a logarithmic number of steps.
(defun my-mult (a b &optional (result 0))
(cond ((zerop b) result)
((evenp b) (my-mult (double a) (half b) result))
(t (my-mult a (- b 1) (+ a result)))))
SICP Exercise 1.22
Most Lisp implementations include a primitive called runtime that returns an integer that specifies the amount of time the system has been running (measured, for example, in microseconds). The following timed-prime-test procedure, when called with an integer n, prints n and checks to see if n is prime. If n is prime, the procedure prints three asterisks followed by the amount of time used in performing the test.
(define (timed-prime-test n)
(newline)
(display n)
(start-prime-test n (runtime)))
(define (start-prime-test n start-time)
(if (prime? n)
(report-prime (- (runtime) start-time))))
(define (report-prime elapsed-time)
(display " *** ")
(display elapsed-time))
Using this procedure, write a procedure search-for-primes that checks the primality of consecutive odd integers in a specified range. Use your procedure to find the three smallest primes larger than 1000; larger than 10,000; larger than 100,000; larger than 1,000,000. Note the time needed to test each prime. Since the testing algorithm has order of growth of (n), you should expect that testing for primes around 10,000 should take about 10 times as long as testing for primes around 1000. Do your timing data bear this out? How well do the data for 100,000 and 1,000,000 support the n prediction? Is your result compatible with the notion that programs on your machine run in time proportional to the number of steps required for the computation?
;;; Redefine given functions for common lisp
(defun smallest-divisor (n)
(find-divisor n 2))
(defun find-divisor (n test-divisor)
(cond ((> (square test-divisor) n) n)
((dividesp test-divisor n) test-divisor)
(t (find-divisor n (+ test-divisor 1)))))
(defun dividesp (a b) (zerop (mod b a)))
(defun square (x) (* x x))
(defun primep (n) (= n (smallest-divisor n)))
(defun timed-prime-test (n)
(print n)
(start-prime-test n (get-internal-run-time)))
(defun start-prime-test (n start-time)
(if (primep n)
(report-prime (- (get-internal-run-time) start-time))))
(defun report-prime (elapsed-time)
(print '***)
(print elapsed-time))
(defun search-for-primes (start end)
(loop for i from start to end do (timed-prime-test i)))
at
Sunday, November 23, 2008
Labels:
Computer Science,
Lisp,
SICP
Posted by
Billy
0
comments
Exercise 1.3
Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
(defun square (x) (* x x))
(defun sum-of-squares (lst)
(apply #'+ (mapcar #'square lst)))
(defun get-largest-2 (lst)
(when (>= (length lst) 2)
(let ((sorted-lst (sort lst #'>)))
(list (first sorted-lst)
(second sorted-lst)))))
;;; This does better and takes any number of arguments
(defun sum-sqr-lrgst (lst)
(sum-of-squares (get-largest-2 lst)))
Exercise 1.8
Newton's method for cube roots is based on the fact that if y is an approximation to the cube root of x, then a better approximation is given by the value
(x/y^2 + 2y)/3
Use this formula to implement a cube-root procedure analogous to the square-root procedure.
(defconstant +tolerance+ 0.001)
(defun cube (x) (* x x x))
(defun good-enough-p (guess x)
"Returns true if the cube of the guess differs from x by less
than the tolerance"
(< (abs (- (cube guess) x)) +tolerance+))
(defun improve (guess x)
"Returns a better approximation of the cube root of x"
(/ (+ (/ x
(square guess))
(* 2 guess))
3))
(defun cube-rt-iter (guess x)
(if (good-enough-p guess x)
guess
(cube-rt-iter (improve guess x) x)))
(defun cube-rt (x)
"Calculates the cube root of x"
(cube-rt-iter 1.0 x))
November 10, 2008
at
Monday, November 10, 2008
Posted by
Billy
0
comments
I am creating a Java web application using Spring and Hibernate. Although I clearly see the benefit of using the Spring framework and Hibernate object/relational mapping tool, configuring it properly can cause some headaches.
Recently I was using Spring's HibernateTemplate to retrieve a list of users from my database. After successfully running a simple query, I then wanted to return the users starting at result number 10 instead of 0. I scanned HibernateTemplate's api to no avail, then searched Google and, to my surprise, found there was no way to return specific rows using HibernateTemplate. The forum posts suggested using Hibernate session instead.
I added a SessionFactory to my class and changed my query code to something like this:
return sessionFactory.getCurrentSession().createQuery("FROM User")
.setMaxResults(10).setFirstResult(10).list();
I confidently ran the code and received the following error:
- Method execution failed:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
This error happened because I did not have my transaction managment configured properly. HibernateTemplate handles this on its own, but when using Hibernate sessions directly, put something like this in your Spring bean files:
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven />
<!-- a PlatformTransactionManager is still required -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
More information can be found in the Spring documentation.
November 8, 2008
at
Saturday, November 08, 2008
Labels:
Computer Science,
Lisp,
Project Euler
Posted by
Billy
0
comments
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?
This Common Lisp solution uses the Sieve of Eratosthenes algorithm to find all the prime numbers under a million then returns the 10001st prime.
(defconstant +max+ 1000000)
(defun range (start end)
"Creates a list of integers from start to end"
(loop for i from start to end collect i))
(defun e.6 ()
(let ((limit (sqrt +max+))
(lst (range 2 +max+)))
(loop for i in lst until (> i limit) do
;; Delete all multiples of i from the list
(delete-if #'(lambda (x)
(and (not (eq x i))
(zerop (mod x i))))
lst))
;; The resulting list is a list of all prime numbers
;; up to +max+. Get the 10001st prime number
(nth 10000 lst)))
Subscribe to:
Posts (Atom)