I'm working through the common divisibility tests, and implementing them in Racket. I'm working on divisible by three, for which I thought it'd be nice to keep summing until I got to a single digit (which I can then check for divisibility by 3).
My code is here, but it feels like there are rather a lot of steps, and I wonder if there's a way to make it feel a bit less imperative.
(define (digits n)
(cond
[(zero? n) '()]
[else (cons (remainder n 10) (digits (quotient n 10)))]))
(define (digisum n)
(apply + (digits n)))
(define (repeated-digit-sum x)
(let ([ds (digisum x)])
(if (< ds 10) ds
(repeated-digit-sum ds))))
1 Answer 1
By the way, the fastest way to see if a number is divisible by three is to use (zero? (remainder n 3))
. If you want to do the digit summing for fun, fine, but it will make your code slower.
So, one way to sum the digits is to extract digits directly during the summing process, rather than building a list of digits first.
(define (digisum n)
(let loop ((sum 0) (n n))
(define-values (q r) (quotient/remainder n 10))
(if (zero? n)
sum
(loop (+ sum r) q))))
Alternatively, you can use a for
comprehension for this:
(define (in-digits n (base 10))
(make-do-sequence
(thunk (values (curryr remainder base)
(curryr quotient base)
n
positive?
#f #f))))
(define (digisum n)
(for/sum ((digit (in-digits n)))
digit))
-
\$\begingroup\$ Yep. I actually have test cases using a generalised modulo function. This is really just an exercise is learning language features. \$\endgroup\$upasaka– upasaka2015年01月21日 07:11:52 +00:00Commented Jan 21, 2015 at 7:11