Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the sum of a digits of a number in Scheme?

I want to calculate the sum of digits of a number in Scheme. It should work like this:

>(sum-of-digits 123)
 6

My idea is to transform the number 123 to string "123" and then transform it to a list '(1 2 3) and then use (apply + '(1 2 3)) to get 6.

but it's unfortunately not working like I imagined.

>(string->list(number->string 123))
'(#\1 #\2 #\3)

Apparently '(#\1 #\2 #\3) is not same as '(1 2 3)... because I'm using language racket under DrRacket, so I can not use the function like char->digit.

Can anyone help me fix this?

like image 358
bearzk Avatar asked Dec 09 '25 02:12

bearzk


1 Answers

An alternative method would be to loop over the digits by using modulo. I'm not as used to scheme syntax, but thanks to @bearzk translating my Lisp here's a function that works for non-negative integers (and with a little work could encompass decimals and negative values):

(define (sum-of-digits x) 
  (if (= x 0) 0 
      (+ (modulo x 10) 
         (sum-of-digits (/ (- x (modulo x 10)) 10)))))
like image 78
Stephen Rudolph Avatar answered Dec 11 '25 15:12

Stephen Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!