语言方案:找到适当的除数之和 [英] Language Scheme: find the sum of proper divisors

查看:34
本文介绍了语言方案:找到适当的除数之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何编写一个函数来计算大于 1 的整数的真除数之和.

I am wondering how to write a function calculating the sum of proper divisors of a integer greater than 1.

(define (sum-of-proper-divisors n)
          (cond
           [(= n 1) 1]
           [(= 0 (remainder n (sub1 n)))
            (+ (remainder n (sub1 n)) (sum-of-proper-divisors (sub1 (sub1 n))))]
           [else (sum-of-proper-divisors (sub1 n))]))

这是我写的代码,但是,它不起作用.它永远不会停止评估,因为它总是会做 n-1.我不知道如何解决这个问题.此外,可能还有其他问题.当除数变为 1 时,如何设置使函数停止计算的限制?

This is the code that I wrote, however, it does not work. It will never stop evaluating because it will always do n-1. And I don't know how to fix this. Also, there might be other problems. How to put the restriction that makes the function stop evaluating when the divisor becomes 1?

推荐答案

您将要查找其除数的数字 n 与上述除数混淆了.注意 n 永远不会改变,每一步必须修改的是当前被测试的整数(一个可能的除数).为此,您需要传递两个参数:

You're confusing the number n whose divisors you want to find, with said divisors. Notice that n never changes, what must be modified at each step is the current integer being tested (a possible divisor). For that you'll need to pass around two parameters:

(define (sum-of-proper-divisors n i)
  (cond
    [(= i 1) 1]
    [(= (remainder n i) 0)
     (+ i (sum-of-proper-divisors n (sub1 i)))]
    [else (sum-of-proper-divisors n (sub1 i))]))

这样称呼,开头的i必须比n少一个单位:

Call it like this, at the beginning i must be one unit less than n:

(sum-of-proper-divisors 10 9)
=> 8

如果有两个参数让你感到困扰,有几种方法可以传递单个参数,例如使用命名的let:

If having two parameters bothers you there are several ways to pass a single parameter, for instance using a named let:

(define (sum-of-proper-divisors n)
  (let loop ((i (sub1 n)))
    (cond
      [(= i 1) 1]
      [(= (remainder n i) 0)
       (+ i (loop (sub1 i)))]
      [else (loop (sub1 i))])))

这篇关于语言方案:找到适当的除数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆