; Recursion with integers ; recursion when the input is natural number (nonnegative integer) ; ; the principle is similar... we can recurse on problems for which there is ; ; 1) base case, an easy case to answer right away ; ; 2) we can break other problems down into simpler problems (each time we will ; reduce the input integer ; example: factorial ; (factorial n) -> n*(n-1)*(n-2)* ... * 2*1 ; you may have seen this written n! in math class ; to write a procedure for factorial we need ; 1) base case: 0! = 1, (factorial 0) --> 1 ; ; 2) (factorial n) -> n*(n-1)*(n-2)* ... * 2*1 -> (* n (factorial (- n 1))) ; (define factorial (lambda (n) (if (= n 0) 1 (* n (factorial (- n 1)))))) ; write a procedure: sum-of-digits, which takes a natural number and ; returns the sum of its digits ; break this into two cases: ; 1) base case: input n is a single digit number, test with (< n 10) ; in this case we wnat to return n ; 2) try to break down more difficult cases ; given a number n, is there a way I can just take off a digit? ; (sum-of-digits n) --> (+ (remainder n 10) (sum-of-digits (quotient n 10))) ; Procedure: SUM-OF-DIGITS returns the sum of the digits of the input number ; ; Given: N, a natural number ; ; Result: SUM-OF-DIGITS, a natural number ; ; Preconditions: none ; ; Postconditions: SUM-OF-DIGITS is the sum of the digits of N (define sum-of-digits (lambda (n) (if (< n 10) n (+ (remainder n 10) (sum-of-digits (quotient n 10))))))