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)
    [(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))))

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)
        (loop (+ sum r) q))))

Alternatively, you can use a for comprehension for this:

(define (in-digits n (base 10))
   (thunk (values (curryr remainder base)
                  (curryr quotient base)
                  #f #f))))

(define (digisum n)
  (for/sum ((digit (in-digits n)))
  • \$\begingroup\$ Yep. I actually have test cases using a generalised modulo function. This is really just an exercise is learning language features. \$\endgroup\$ – upasaka Jan 21 '15 at 7:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.