Skip to content
Browse files

adding 1.26

  • Loading branch information...
1 parent 8984747 commit ec2b537a67b05d57fe624398cb5b83bdc7cf5fe5 @cosmin committed
Showing with 30 additions and 0 deletions.
  1. +30 −0 exercise-1-26.ss
View
30 exercise-1-26.ss
@@ -0,0 +1,30 @@
+(define (even? n) (= 0 (remainder n 2)))
+
+;; linear recursion
+(define (expmod base exp m)
+ (display ".")
+ (cond ((= exp 0) 1)
+ ((even? exp)
+ (remainder (square (expmod base (/ exp 2) m))
+ m))
+ (else
+ (remainder (* base (expmod base (- exp 1) m))
+ m))))
+
+;; tree recursion
+(define (expmod base exp m)
+ (display ".")
+ (cond ((= exp 0) 1)
+ ((even? exp)
+ (remainder (* (expmod base (/ exp 2) m)
+ (expmod base (/ exp 2) m))
+ m))
+ (else
+ (remainder (* base (expmod base (- exp 1) m))
+ m))))
+
+
+;; compared to using square, using inlined multiplication does not
+;; result in twice as many calls to expmod. Instead it results in
+;; exponential growth because the entire subtree has to be recomputed
+;; twice at each level.

0 comments on commit ec2b537

Please sign in to comment.
Something went wrong with that request. Please try again.