Digital Root of Large Integers using Python Recursion
In this tutorial, we are going to see how to find Digital Roots of fairly large Integers using Recursion in Python.
The digital root of an Integer can be found by doing the sum of all the digits of a given integer till a single digit integer is left. This single digit integer is the digital root of the given integer. If the sum of all the digits of given integer results in a two or three digit integer then do the sum of the digits again till a single-digit integer is left.
N = 9956782345098712347865490832469987 S1 = Sum of all the digits of N = 187 S2 = Sum of all the digits of S1 = 16 SF = Sum of all the digits of S2 = 7 Result: Hence the digital root of the given integer N = 7
def digital_root(n): if(n < 10): return n n=n%10+digital_root(n//10) return digital_root(n) print((digital_root(9956782345098712347865490832469987)))
At first create a function that accepts an integer. Then check if the integer is greater them 10 or not. If the integer is less them 10 then return the number instantly and end the function. If the number is greater then 10 then find out the sum of digit of the given integer recursively by calling the above function.
The process will keep on repeating till we get sum of all the digits of the given integer. Then again check if our final number is single digit or not by comparing it with 10. If the number is single digit return it. The returned number is our digital root. If the number is not a single digit number then repeat the process till a single digit is left.
So with this process, we are able to find the digital root of large integers using Recursion in Python.