11-06-2013 Supplement

posted Nov 6, 2013, 6:36 PM by Samuel Konstantinovich   [ updated Nov 6, 2013, 8:36 PM ]
Solutions :

Hanoi 1:
(define (hanoi n start temp end)
  (if (= n 1)
      (begin
        (display start)(display " to ")(display end)
        (newline)
        )
      (begin
        (hanoi (- n 1) start end temp)
        (hanoi 1 start temp end) 
        (hanoi (- n 1) temp start end)
        )))

Hanoi 2: (less elegant)
(define (hanoi n start temp end)
  (if (= n 1)
      (begin
        (display start)(display " to ")(display end)
        (newline)
        )
      (begin
        (hanoi (- n 1) start end temp)
        (display start)(display " to ")(display end)
        (newline)
        (hanoi (- n 1) temp start end)
        )))


IsPrime 1:
(define (primeHelp n current)
  (cond
    ( (= n 1) #f)
    ( (= n 2) #f)
    ( (> current (sqrt n)) #t)
    ( (= (remainder n current) 0) #f)
    ( else (primeHelp n (+ current 1)))))

(define (isPrime n)
  (primeHelp n 2))

Is Prime 2: (improved)
(define (primeHelp n current)
  (cond
    ( (< n 0) (primeHelp (- n) current))
    ( (< n 2) #f)
    ( (> current (sqrt n)) #t)
    ( (= (remainder n current) 0) #f)
    ( else (primeHelp n (+ current 1)))))

(define (isPrime n)
  (primeHelp n 2))


Comments