3
\$\begingroup\$

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))))
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Jan 20, 2015 at 23:05
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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))
answered Jan 21, 2015 at 3:25
\$\endgroup\$
1
  • \$\begingroup\$ Yep. I actually have test cases using a generalised modulo function. This is really just an exercise is learning language features. \$\endgroup\$ Commented Jan 21, 2015 at 7:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.