What is a Digital root? if you have done little competitive programming or practice for Data Structure or anything else you have got a problem where you need to sum all digits of the number and do this process until the number becomes a single-digit number. so that is Digital Root, let's talk about it.
So you might have seen digital root , some Example
Examples:
123 => 1 + 2 + 3 => 6
455 => 4 + 5 + 5 => 14 => 1+4 = 5
So here you can attempt brute force too. but that will be slow. Then how will you solve this problem?
Some points which we use in the digital root concept(properties),
- when you multiply any number(>0) by 9 then the sum of all digits of that number will always be 9. Example : 345*9 = 3105 => 3+1+0+5 => 9 , you can check yourself this condition (try different numbers)
- When we add 9 to any number(here add means concatenating ) sum of all digits won't get effected, Example : 345 => 3+4+5 => 12 => 1+2 => 3, now add 9 , 3459 => 21 => 2+1=>3
- when we divide any number by 9, then what remainder we get is the same as the digital root of that number. Example : 15/9 => 6 and 15=> 1+5=>6
- Any Perfect Square's digital root will be 1,4,7,9 (16=>1+6=>7, 36=>3+6=>9 etc)
So Condition for digital root will be,
Here n = number, b= base value (for decimal b=10)
if n==0 then digital_root(n) = 0
if n!=0 && n%(b-1) ==0 then digital_root(n) = b-1
if n%(b-1) != 0 then digital_root(n) = n mod (b-1)
OR
we can put this in little more simpler form,
if n==0 then digital_root(n) = 0
else , 1 + ( (n-1)%9)
So let's put this all in code
C++:
Python3:
LeetCode Question About Digital Root
If you want to know more about Digital Root --> Wikipedia
Thank You 😊😊
Comments
Post a Comment