Funciton/Digital root calculator
Jump to navigation
Jump to search
This is a Funciton program that outputs the digital root of an input number. The input is expected to be an integer (not followed by a newline or any other whitespace). It requires several of the library functions.
I wrote this before I realised there is the efficient formula 1+(n-1)%9
. The program could be a lot smaller if that formula were used.
╓───╖ ║ ‰ ║ ╙─┬─╜ ┌──────────┴────────┐ ╔══════════════════════════╗ ┌────────┴────────┐ ┌─────┴────┐ ║ digital root ║ │ │ ┌─┴─╖ │ ╟──────────────────────────╢ │ │ │ ~ ║ │ ║ ‰(n) = n < 0 ? ‰(~n) : ║ │ │ ╘═╤═╝ │ ║ n < 10 ? n : ║ │ ╔════╗ ┌───╖ │ ┌─┴─╖ │ ║ ‰(‰p(0, n)) ║ │ ║ 10 ╟──┤ < ╟──┘ │ ‰ ║ │ ╚══════════════════════════╝ │ ╚════╝ ╘═╤═╝ ╘═╤═╝ ┌───┴───┐ │ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ │ └──────────┤ ? ╟─────┤ ? ╟──┤ > ║ │ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │ ┌─┴─╖ │ ╔═╧═╗ │ │ ‰ ║ ║ 0 ║ │ ╔═══╗ ╘═╤═╝ ╚═══╝ │ ║ ║ ╔═══╗ ┌─┴──╖ │ ╚═╤═╝ ║ 0 ╟──┤ ‰p ╟─────────────────────┘ ┌────┴────╖ ╚═══╝ ╘════╝ │ str→int ║ ╘════╤════╝ ┌───────────────────────────┐ ┌─┴─╖ │ ╓┬───╖ │ │ ‰ ║ ├─────╫┘‰p ╟──┐ │ ╘═╤═╝ │ ╙────╜ │ │ ┌────┴────╖ │ ╔════╗ │ │ │ int→str ║ │ ║ 10 ║ │ │ ╘════╤════╝ │ ╚═╤══╝ │ │ │ │ ┌─┴──╖ │ │ │ ┌──┤ ÷% ╟──┴────────┐ │ │ │ ╘═╤══╝ │ │ │ │ └───────┐ │ │ │ │ ┌────╖ ┌─┴─╖ │ │ ╔═════════════════════════════╗ │ └──┤ ‰p ╟──┤ + ║ │ │ ║ digital root (helper) ║ │ ╘═╤══╝ ╘═╤═╝ ┌─┴─╖ │ ╟─────────────────────────────╢ │ │ └────┤ · ╟──┘ ║ ‰p(a, n) = ║ │ ┌─┴─╖ ╘═╤═╝ ║ let (q, r) = n ÷% 10; ║ └─────┤ ? ╟────────────┘ ║ n ? ‰p(a + r, q) : a ║ ╘═╤═╝ ╚═════════════════════════════╝ │