如何在Racket中实现递归函数?

时间:2015-02-10 13:16:52

标签: racket tail-recursion

我正在尝试创建一个名为lcm-from-factors的函数,它计算两个数字的最低公倍数(m和n)函数的输入是m-co-groups和n-co-groups,列出所有主要因素和他们的权力。例如,对于m = 2970和n = 163,800,我们将:

m-co-groups ='((2 1)(3 3)(5 1)(7 0)(111)(13 0)) n-co-groups ='((2 3)(3 2)(5 2)(7 1)(11 0)(13 1))

这些是由一个叫做辅因子的函数返回的,这个函数已经给我了。我编写了代码,但函数没有编译,因为我相信我没有正确实现递归。在弄清楚我做错了什么的时候,我感激不尽。我的代码如下。

    (define (lcm-from-factors m n)
        (let-values (((m-co-groups n-co-groups) (co-factor m n)))
            (define (recurse m-co-groups n-co-groups)
                (let* ((a (first(m-co-groups)))
                      (b (first(n-co-groups))))
                   (cond ((>= (rest(a)) (rest(b)))
                         (+ (expt (first(a)) (rest(a))) (recurse (rest(m-co-groups)) (rest(n-co-groups)))))
                         (else (+ (expt (first(b)) (rest(b))) (recurse (rest(m-co-groups)) (rest(n-co-groups))))))))))

1 个答案:

答案 0 :(得分:0)

以下是帮助您入门的踏脚石。 该代码处理m和n具有相同素因子的特定情况。 找出如何处理其他案件是你的工作。

#lang racket
(require math/number-theory)

(define (co-factor m n) (values (factorize m) (factorize n)))
(define (exponent power) (second power))
(define (base power)     (first power))

(define (lcm-from-factors m n)
  (let-values ([(m-co-groups n-co-groups) (co-factor m n)])
    (define (recurse m-co-groups n-co-groups)
      (cond
        [(and (empty? m-co-groups) (empty? n-co-groups))  1]
        [(empty? m-co-groups)                             'something-1]
        [(empty? n-co-groups)                             'something-2]
        [else
         (define a-power (first m-co-groups))
         (define b-power (first n-co-groups))
         (define a-base  (base a-power))
         (define b-base  (base b-power))
         (define a-exp   (exponent a-power))
         (define b-exp   (exponent b-power))
         (cond 
           [(= a-base b-base)   (* (expt a-base (max a-exp b-exp))
                                   (recurse (rest m-co-groups) (rest n-co-groups)))]
           [(< a-base b-base)   'something-3]
           [(> a-base b-base)   'something-4])]))
    (recurse m-co-groups n-co-groups)))

(define x (* (expt 2 3) (expt 3 4)))
(define y (* (expt 2 1) (expt 3 5)))

(lcm-from-factors x y) ; gives 1944
(lcm x y)              ; gives 1944