Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

1.33

  • Loading branch information...
commit d1fd83e6c8a94143ce049a39d9b5a443b58417f1 1 parent 46745e6
@cosmin authored
Showing with 59 additions and 0 deletions.
  1. +59 −0 exercise-1-33.ss
View
59 exercise-1-33.ss
@@ -0,0 +1,59 @@
+(define (inc x) (+ x 1))
+(define (identity x) x)
+
+;; from exercise 1.20
+
+(define (gcd a b)
+ (if (= b 0)
+ a
+ (gcd b (remainder a b))))
+
+;; from exercise 1.27
+
+(define (square x) (* x x))
+
+(define (expmod base exp m)
+ (cond ((= exp 0) 1)
+ ((even? exp)
+ (remainder (square (expmod base (/ exp 2) m)) m))
+ (else
+ (remainder (* base (expmod base (- exp 1) m)) m))))
+
+(define (fermat-test n a)
+ (= (expmod a n n) a))
+
+(define (test-all-starting-with n a)
+ (cond ((= a 0) true)
+ ((fermat-test n a) (test-all-starting-with n (- a 1)))
+ (else false)))
+
+(define (prime? n)
+ (if (> n 1)
+ (test-all-starting-with n (- n 1))
+ #f))
+
+
+;; exercise
+
+(define (filtered-accumulate combiner filter? null-value term a next b)
+ (define (iter a result)
+ (if (> a b)
+ result
+ (iter (next a)
+ (if (filter? a)
+ (combiner (term a) result)
+ result))))
+ (iter a null-value))
+
+
+
+(define (sum-square-of-primes a b)
+ (filtered-accumulate + prime? 0 square a inc b))
+
+(= 87 (sum-square-of-primes 1 10))
+
+(define (sum-relatively-prime-less-then n)
+ (define (relatively-prime? x) (= 1 (gcd x n)))
+ (filtered-accumulate + relatively-prime? 0 identity 1 inc (- n 1)))
+
+(= 20 (sum-relatively-prime-less-then 10)) ; (+ 1 3 7 9)
Please sign in to comment.
Something went wrong with that request. Please try again.