Skip to content

Instantly share code, notes, and snippets.

@venelrene
Created December 17, 2019 15:57
Show Gist options
  • Select an option

  • Save venelrene/ef856e14688aaece87393ba725709c68 to your computer and use it in GitHub Desktop.

Select an option

Save venelrene/ef856e14688aaece87393ba725709c68 to your computer and use it in GitHub Desktop.
A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.
def digital_root(n)
return n if n < 10
until n.to_s.size == 1
n = n.to_s.chars.map(&:to_i).reduce(:+)
end
return n
end
###### Better answer to reminber
def digital_root(n)
n < 10 ? n : digital_root(n.digits.sum)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment