2015/10/10

SICP 問題 2.5

(define (cons a b)
  (* (expt 2 a)
     (expt 3 b)))

(define (car c)
  (define (iter n count)
    (if (< 0 (remainder n 2))
        count
        (iter (/ n 2) (+ count 1))))
  (iter c 0))

(define (cdr c)
  (define (iter n count)
    (if (< 0 (remainder n 3))
        count
        (iter (/ n 3) (+ count 1))))
  (iter c 0))

 
 
始め算術演算を使えって条件を見逃してlogを使って書いたのでそれも.

(define (car c)
  (define (iter n)
    (if (= 0 (modulo n 3))
        (iter (/ n 3))
        (log n 2)))
  (iter c))

(define (cdr c)
  (define (iter n)
    (if (= 0 (modulo n 2))
        (iter (/ n 2))
        (log n 3)))
  (iter c))

© 2022 wat-aro