DAY 7
1

# 07 - Sum of Digits / Digital Root

Don't say so much, just coding...

## Instruction

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.

Examples:

``````   16   -->  1 + 6 = 7
942  -->  9 + 4 + 2 = 15  -->  1 + 5 = 6
132189  -->  1 + 3 + 2 + 1 + 8 + 9 = 24  -->  2 + 4 = 6
493193  -->  4 + 9 + 3 + 1 + 9 + 3 = 29  -->  2 + 9 = 11  -->  1 + 1 = 2
``````

### Ruby

#### Init

``````  def digital_root(n)
# ...
end
``````

#### Sample Testing

``````  Test.assert_equals(digital_root(16), 7)
Test.assert_equals(digital_root(942), 6)
Test.assert_equals(digital_root(132189), 6)
Test.assert_equals(digital_root(493193), 2)
``````

### Javascript

#### Init

``````  function digital_root(n) {
// ...
}
``````

#### Sample Testing

``````  Test.assertEquals( digital_root(16), 7 )
Test.assertEquals( digital_root(456), 6 )
``````

# Solution

### Ruby

``````  # Solution 1
def digital_root(n)
recursive = n.to_s.split('').map(&:to_i).sum
recursive >= 10 ? digital_root(recursive) : recursive
end

# Solution 2
def digital_root(n)
return n if n < 10
digital_root(n.to_s.chars.map(&:to_i).reduce(&:+))
end

# Solution 3
def digital_root(n)
n < 10 ? n : digital_root(n.to_s.chars.map(&:to_i).reduce(:+))
end
``````

### Javascript

``````  // Solution 1
function digital_root(n) {
recursive = n.toString().split('').reduce((sum, s) => {
return sum += Number(s);
}, 0);

return recursive < 10 ? recursive : digital_root(recursive);
}

// wait, what?
function digital_root(n) {
return (n - 1) % 9 + 1;
}
``````