S2. Sample Recursive Functions

posted Oct 9, 2012, 5:22 AM by Samuel Konstantinovich   [ updated Nov 15, 2012, 5:12 AM ]
;a divisible function to help write other functions
(define (divisible?  a b)
  (= 0 (remainder a b)))

;a different way of writing your own gcf
;it doesn't check all integers for divisibility
(define (gcf a b)
  (if (= b 0)
      a
      (gcf b (remainder a b))))

;a different way of writing prime using gcf or divisible 
;in the help function
(define (prime? n)
  (primehelp n 2))

(define (primehelp n x)
  (cond
    ((>(gcf n x) 1) #f);ALTERNATE:  ((divisible n x) #f)
    ((> x (sqrt n)) #t)
    (else (primehelp n (+ x 1)))))

;improved sum function with if statement
;to check the order of the terms. This
;allows you to put two integers in ANY order
;and still calculate the sum correctly

;Regular recursive sumAtoB:
(define (sumAtoB a b)
  (if (> b a)
      (helpsumab a b)
      (helpsumab b a)))

(define (helpsumab a b)
  (if (> a b)
      0
      (+ a (helpsumab (+ a 1) b))))


;ITERATIVE SOLUTION to sumAtoB:
(define (sumAtoB a b)
  (if (> b a)
      (itrsumab a b 0)
      (itrsumab b a 0)))

;headsumab is the helper for (sumAtoB)
(define (itrsumab a b s)
  (if (> a b)
      s
     (itrsumab (+ a 1) b (+ s a)))) 

Comments