summaryrefslogtreecommitdiff
path: root/coding-exercises/1/31.rkt
diff options
context:
space:
mode:
Diffstat (limited to 'coding-exercises/1/31.rkt')
-rw-r--r--coding-exercises/1/31.rkt31
1 files changed, 31 insertions, 0 deletions
diff --git a/coding-exercises/1/31.rkt b/coding-exercises/1/31.rkt
new file mode 100644
index 0000000..10f52c5
--- /dev/null
+++ b/coding-exercises/1/31.rkt
@@ -0,0 +1,31 @@
+#lang racket
+(require sicp)
+
+(define (id x) x)
+
+(define (factorial n)
+ (product id 1 inc n))
+
+(define (product term a next b)
+ (define (iter result a)
+ (if (> a b)
+ result
+ (iter (* (term a) result) (next a))))
+ (iter 1 a))
+
+(define (even? x)
+ (= (remainder x 2) 0))
+
+(define (pi-product n)
+ (/ (product (lambda (x)
+ (if (even? x)
+ x
+ (+ x 1)))
+ 2 inc n)
+ (product (lambda (x)
+ (if (even? x)
+ (+ x 1)
+ x))
+ 2 inc n)))
+
+(* 1.0 (pi-product 1000))