问题
I need to write a function in scheme which calculates the sum of square digits.
ex - (sum-of-digits 130)
> 10
This is my function.
(define (sum-of-digits x)
(if (= x 0) 0
(+ (modulo x 10) (sum-of-digits (/ (- x (modulo x 10)) 10)))))
it doesn't work for some numbers. When I entered (sum-of-digits 130) , it returns 4. How can i fix this ?
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
How can I do this using the function sum of sum-of-digits above?
回答1:
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)))))
For the second part of the question:
(define (stop? x)
(let ((sum (sum-of-digits x)))
(if (member sum '(0 1 4 16 20 37 42 58 89 145)) #t #f)))
来源:https://stackoverflow.com/questions/42958757/find-sum-of-the-squares-of-the-digits-of-a-number-in-scheme