find sum of the squares of the digits of a number in scheme

a 夏天 提交于 2019-12-12 02:29:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!