Funciton/Digital root calculator

From Esolang
Jump to navigation Jump to search

Back to Funciton

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

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. Nevertheless, this demonstrates recursion in Funciton as well as some library functions such as ÷% (division and modulo).


                        ╓───╖
                        ║ ‰ ║
                        ╙─┬─╜
               ┌──────────┴────────┐
      ┌────────┴────────┐    ┌─────┴────┐
      │                 │  ┌─┴─╖        │        ╔════════════════════════════════╗
      │                 │  │ − ║        │        ║  digital root                  ║
      │                 │  ╘═╤═╝        │        ╟────────────────────────────────╢
      │  ╔════╗  ┌───╖  │  ┌─┴─╖        │        ║  If ↓ < 0, negate              ║
      │  ║ 10 ╟──┤ < ╟──┘  │ ‰ ║        │        ║  If ↓ < 10, answer is ↓        ║
      │  ╚════╝  ╘═╤═╝     ╘═╤═╝    ┌───┴───┐    ║  Else call ‰p and then repeat  ║
      │          ┌─┴─╖     ┌─┴─╖  ┌─┴─╖     │    ╚════════════════════════════════╝
      └──────────┤ ? ╟─────┤ ? ╟──┤ > ║     │
                 ╘═╤═╝     ╘═╤═╝  ╘═╤═╝     │
                 ┌─┴─╖       │    ╔═╧═╗     │
                 │ ‰ ║            ║ 0 ║     │            ╔═══╗
                 ╘═╤═╝            ╚═══╝     │            ║   ║
          ╔═══╗  ┌─┴──╖                     │            ╚═╤═╝
          ║ 0 ╟──┤ ‰p ╟─────────────────────┘            ┌─┴─╖
          ╚═══╝  ╘════╝                                  │ 《 ║
                                                         ╘═╤═╝
            ┌───────────────────────────┐                ┌─┴─╖
            │     ╓┬───╖                │                │ ‰ ║
            ├─────╫┘‰p ╟──┐             │                ╘═╤═╝
            │     ╙────╜  │             │                ┌─┴─╖
            │     ╔════╗  │             │                │ 》 ║
            │     ║ 10 ║  │             │                ╘═╤═╝
            │     ╚═╤══╝  │             │                  │
            │     ┌─┴──╖  │             │
            │  ┌──┤ ÷% ╟──┴────────┐    │
            │  │  ╘═╤══╝           │    │    ╔═════════════════════════════╗
            │  │    └───────┐      │    │    ║  digital root (helper)      ║
            │  │  ┌────╖  ┌─┴─╖    │    │    ╟─────────────────────────────╢
            │  └──┤ ‰p ╟──┤ + ║    │    │    ║  → is an accumulator        ║
            │     ╘═╤══╝  ╘═╤═╝  ┌─┴─╖  │    ║  If → = 0, result is ←      ║
            │       │       └────┤ · ╟──┘    ║  Else, add last digit of →  ║
            │     ┌─┴─╖          ╘═╤═╝       ║  to ← and recurse           ║
            └─────┤ ? ╟────────────┘         ╚═════════════════════════════╝
                  ╘═╤═╝
                    │