简体   繁体   English

计划中的倍数之和

[英]Sum of Multiples in Scheme

so I am very new to Scheme and functional programming as a whole. 所以我对Scheme和函数式编程很新。 I am trying to write a program that finds the sum of all the multiples of 3 or 5 below 1000. This is my attempt so far : 我正在尝试编写一个程序,找到所有3或5的倍数低于1000的总和。这是我到目前为止的尝试:

(define (sum-of-multiples n)
; Start = 0, End = n, Sum = 0.
(get-sum 0 n 0)
)

; A recursive loop that starts at 0 and ends with given n (1000).
(define (get-sum start end sum)
   (cond
   ; Stopping case.
   ((= start end) sum)
   ; If start counter is divisible by 3, add to sum.
   ((= (remainder start 3) 0) (get-sum (+ start 1) end (+ start sum)))
   ; If start counter is divisible by 5, add to sum.
   ((= (remainder start 5) 0) (get-sum (+ start 1) end (+ start sum)))
   ; Otherwise just increment start counter.
   (get-sum (+ start 1) end sum))
)

(display (sum-of-multiples 1000))
(display " ")

I am not sure if the thing wrong with my code at the moment is because of Scheme syntax issues or my attempt at recursion to solve the problem. 我不确定我的代码目前的错误是由于Scheme语法问题还是我尝试递归来解决问题。 As I am not great at either of those things. 因为我对这两件事都不擅长。

When I run this code I just get '0' displayed. 当我运行此代码时,我只显示“0”。

Any help with finding and fixing my errors would be great. 找到并修复错误的任何帮助都会很棒。

Thanks! 谢谢!

You left out the else on the "all other cases" case; 你在“所有其他案件”案件中遗漏了else ; it should be 它应该是

(else (get-sum (+ start 1) end sum))

An attempt at explaining where you got 0 from: 试图解释你从哪里得到0:

A cond clause has the form (condition expression) , so your condition is get-sum . cond子句具有形式(condition expression) ,因此您的条件是get-sum
Just like else , this condition is never false. 就像else情况else ,这种情况永远不会错。

There is also an implicit begin after the condition, so what you have is equivalent to 在条件之后还有一个隐含的begin ,所以你所拥有的相当于

(else (begin (+ start 1) end sum))

And the result of that is the value of the last expression in the begin block, which is sum . 结果就是begin块中最后一个表达式的值,即sum

Since sum is 0 when you reach that condition for the first time, the result is 0. 由于当您第一次达到该条件时sum为0,因此结果为0。

cond format is: cond格式是:

(cond (<condition> <expr>)
       .
       .
      (else <expr>))

In your code there is no else . 在你的代码中没有else get-sum function (with some reformatting) should be: get-sum函数(有些重新格式化)应该是:

(define (get-sum start end sum)
   (cond
      ((= start end) sum)
      ((= (remainder start 3) 0)
       (get-sum (+ start 1) end (+ start sum)))
      ((= (remainder start 5) 0)
       (get-sum (+ start 1) end (+ start sum)))
      (else
       (get-sum (+ start 1) end sum))))

With this fix, your code displays 233168 . 使用此修复程序,您的代码显示233168 I didn't check your algorithm, but this result looks better than 0 :) 我没有检查你的算法,但这个结果看起来好于0 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM