見習村07 - Sum of Digits / Digital Root

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:

1
2
3
4
   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

1
2
3
def digital_root(n)
# ...
end

Sample Testing

1
2
3
4
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

1
2
3
function digital_root(n) {
// ...
}

Sample Testing

1
2
Test.assertEquals( digital_root(16), 7 )
Test.assertEquals( digital_root(456), 6 )

Thinking

想法(1): 將傳進來的值,先切開之後進行相加
想法(2): 需要判斷如果是兩位數以上的話,還需要在進行上述的動作,可以聯想到遞迴

https://ithelp.ithome.com.tw/upload/images/20200922/20120826PSUp8bSOU0.jpg
圖片來源:Unsplash Alexis Brown

Hint & Reference

Solution

Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 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

1
2
3
4
5
6
7
8
9
10
11
12
13
// 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;
}