HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Digit Summing Function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
summingdigitfunction

Problem

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

Solution

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

Code Snippets

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

Context

StackExchange Code Review Q#78175, answer score: 2

Revisions (0)

No revisions yet.