;; Iterative Version ;; Return the nth harmonic number (define iter-harm (lambda (n) (harm-helper 0 n))) (define harm-helper (lambda (sum n) ; compute (sum + H_n) as (sum + 1/n) + H_{n-1} (if (= n 0) sum (harm-helper (+ (/ 1 n) sum) (- n 1))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Iterative Version ;; Return m*n, whre m is a number ;; and n is a nonnegative integer (define iter-mult (lambda (m n) (mult-helper 0 m n))) ;; Add m*n to product and return it (define mult-helper (lambda (prod m n) ; compute prod + m*n as (prod + m) + m*(n-1) (if (= n 0) prod (mult-helper (+ prod m) m (- n 1))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Iterative Version ;; Count the number of 6's in the decimal representation ;; of nonnegative number n (define iter-number-of-6s (lambda (n) (number-of-6s-helper 0 n))) ;; Add the number of 6's in the decimal representation (D.R.) of n to count ;; and return it (define number-of-6s-helper ;; computes (count + number of 6's in the D.R. of n) as ;; (count + 1 + (number of 6's in the D.R. of floor(n/10)) if the last digit of n is 6 ;; (count + (number of 6's in the D.R. of floor(n/10)) otherwise (lambda (count n) (if (= n 0) count (number-of-6s-helper (+ count (if (= (remainder n 10) 6) 1 0)) (quotient n 10))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Iterative Version ;; Russian Multiplication ;; Return m*n, whre m is a number ;; and n is a nonnegative integer (define iter-r-mult (lambda (m n) (r-mult-helper 0 m n))) ;; Add m*n to prod and return it (define r-mult-helper ;; computes (prod + m*n) as ;; (prod + m) + (2*m + floor(n/2)) if n is odd ;; prod + (2*m + floor(n/2)) if n is even (lambda (prod m n) (if (= n 0) prod (r-mult-helper (+ prod (if (odd? n) m 0)) (+ m m) (quotient n 2))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Iterative Version ;; Return sum of digits in the decimal representation of a ;; nonnegative integer n (define iter-sum-of-digits (lambda (n) (sum-of-digits-helper 0 n))) ;; Add the sum of digits in the decimal representation (D.R.) of n to sum ;; and return it (define sum-of-digits-helper ;; computes (sum + sum of digits of n) as ;; (sum + the rightmost digit in the D.R. of n) ;; + (sum of digits in the D.R. of floor(n/10)) (lambda (sum n) (if (= n 0) sum (sum-of-digits-helper (+ sum (remainder n 10)) (quotient n 10)))))