求scheme中数字的平方和 [英] find sum of the squares of the digits of a number in scheme
本文介绍了求scheme中数字的平方和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在 scheme 中编写一个函数来计算平方数之和.
I need to write a function in scheme which calculates the sum of square digits.
ex - (sum-of-digits 130)
> 10
这是我的职责.
(define (sum-of-digits x)
(if (= x 0) 0
(+ (modulo x 10) (sum-of-digits (/ (- x (modulo x 10)) 10)))))
它不适用于某些数字.当我输入 (sum-of-digits 130) 时,它返回 4.我该如何解决这个问题?
it doesn't work for some numbers. When I entered (sum-of-digits 130) , it returns 4. How can i fix this ?
我还需要使用这个函数来找到 0,1,4,16,20,37,42,58,89,145 的停止号码
Also I need to use this function to find the stop numbers which are 0,1,4,16,20,37,42,58,89,145
ex :- (stop? 42)
#t
(stop? 31)
#f
如何使用上述数字总和的函数 sum 来做到这一点?
How can I do this using the function sum of sum-of-digits above?
推荐答案
您实际上忘记对每个数字进行平方,还有一种更简单的方法来获得商:
You forgot to actually square each digit, and there's a simpler way to obtain the quotient:
(define (sum-of-digits x)
(if (= x 0)
0
(+ (sqr (modulo x 10))
(sum-of-digits (quotient x 10)))))
对于问题的第二部分:
(define (stop? x)
(let ((sum (sum-of-digits x)))
(if (member sum '(0 1 4 16 20 37 42 58 89 145)) #t #f)))
这篇关于求scheme中数字的平方和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文