Instantly share code, notes, and snippets.

# ericnormand/00 Super Digit.md

Created September 12, 2022 15:11
Show Gist options
• Save ericnormand/049ace0f757e468f7536c7fc181a90a4 to your computer and use it in GitHub Desktop.

Super Digit

This is kind of a contrived problem, but it's the kind that breeds lots of interesting implementations and tests your understanding of lower-level details. So let's do it!

You're given an integer `n` and an integer `k`. There is an integer `p` that is `k` instances of the digits of `n` concatenated together. For example:

``````n=123, k=3 -> p=123123123
n=32, k=6 -> p=323232323232
n=24543, k=125 -> p=245432454324543245432454324543...
``````

Now, take that number `p` and find its superdigit. The superdigit is defined as follows:

``````superdigit(d) = d                             if # of digits = 1
superdigit(d) = superdigit(sum(digits of d))  otherwise
``````

That is, if the number has one digit, the superdigit is the number. (Example: `superdigit(4)=4`). Otherwise, sum the digits and take the superdigit of the result. (Example: `superdigit(23)=superdigit(2+3)=5`).

Your task is to write a function that calculates the superdigit of `n` and `k`.

Examples

```;           n  k
(superdigit 1  1) ;=> 1
(superdigit 10 2) ;=> 2
(superdigit 11 3) ;=> 6
(superdigit 38 7) ;=> 5
(superdigit 38789789374294723947328946 1000000000000000) ;=> 8```

Notes

• Be sure that it works with very large strings of digits, such as with `n>10^20, k>1 000 000 000`.

Thanks to this site for the problem idea, where it is rated Expert in Java. The problem has been modified.

### arthuronunes commented Feb 28, 2023

```(defn sum [nums]
(->> (partition-all 1 (str nums))
(reduce #(+ %1 (parse-long (str (first %2)))) 0)))

(defn superdigit [n k]
(loop [nums (sum n)
multiplied? false]
(let [one-digit? (< nums 10)]
(if (and one-digit? multiplied?)
nums
(recur (if one-digit? (* nums k) (sum nums))
(if multiplied? true one-digit?))))))```