首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >难以取n个数乘积的第n根

难以取n个数乘积的第n根
EN

Stack Overflow用户
提问于 2019-02-09 18:38:35
回答 1查看 191关注 0票数 3

我试图建立一个递归函数,它包含一个n个数字的列表。这个函数应该做的是取n个数的乘积,然后取第n个根。我得到了n个数字的乘积,但不知道如何实现第n个根。

我尝试的是实现expt 函数,但是在递归中没有正确实现它。此外,在尝试实现此函数时,我也不知道如何才能将expt函数提供给nth根。(y=1/n).

代码语言:javascript
复制
(define (nth-root-of-product-of-numbers lst)
  (cond [(empty? lst) 1]
        [else (* (first lst) (nth-root-of-product-of-numbers (rest lst)))]))

因此,上面的代码正确地生成了n个数字列表上的产品,但是它不能补偿n个根问题。样本输入如下:

代码语言:javascript
复制
(check-within
(nth-root-of-product-of-numbers (cons 9 (cons 14 (cons 2 empty)))) 6.316359598 0.0001)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-09 23:29:35

您需要计算递归末尾的第n根。有几种方法可以做到这一点--例如,定义一个帮助过程,用于查找产品并在计算完产品后取根:

代码语言:javascript
复制
(define (nth-root-of-product-of-numbers lst)
  (define (product lst)
    (cond [(empty? lst) 1]
          [else (* (first lst) (product (rest lst)))]))
  (expt (product lst) (/ 1 (length lst))))

一个更有效的解决方案是编写一个尾递归过程,并传递元素的数量,以避免在最后计算length。下面是如何使用let

代码语言:javascript
复制
(define (nth-root-of-product-of-numbers lst)
  (let loop ((lst lst) (acc 1) (n 0))
    (cond [(empty? lst)
           (expt acc (/ 1 n))]
          [else
           (loop (rest lst) (* (first lst) acc) (add1 n))])))

一个更惯用的解决方案是使用内置过程来计算产品:

代码语言:javascript
复制
(define (nth-root-of-product-of-numbers lst)
  (expt (apply * lst) (/ 1 (length lst))))

无论如何,它的工作方式与预期的一样:

代码语言:javascript
复制
(nth-root-of-product-of-numbers (list 9 14 2))
=> 6.316359597656378
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54609436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档