Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to find sum of digits until it is one digit number in Python
Sometimes we need to keep adding the digits of a number repeatedly until we get a single digit. This process is called finding the digital root of a number.
So, if the input is like 9625, then the output will be 4 because:
- 9 + 6 + 2 + 5 = 22
- 2 + 2 = 4
Using Recursive Approach
We can solve this by recursively summing the digits until we get a single digit ?
import math
class Solution:
def solve(self, n):
if n < 10:
return n
digit_sum = 0
length = math.floor(math.log(n, 10) + 1)
while length > 0:
digit_sum += n % 10
n //= 10
length -= 1
return self.solve(digit_sum)
# Test the solution
ob = Solution()
result = ob.solve(9625)
print(f"Digital root of 9625: {result}")
Digital root of 9625: 4
Using Simple Iterative Approach
A simpler approach without using logarithms ?
def digital_root(n):
while n >= 10:
digit_sum = 0
while n > 0:
digit_sum += n % 10
n //= 10
n = digit_sum
return n
# Test with examples
numbers = [9625, 123, 999, 0]
for num in numbers:
result = digital_root(num)
print(f"Digital root of {num}: {result}")
Digital root of 9625: 4 Digital root of 123: 6 Digital root of 999: 9 Digital root of 0: 0
Mathematical Formula Approach
There's also a mathematical shortcut using modular arithmetic ?
def digital_root_formula(n):
if n == 0:
return 0
return 1 + (n - 1) % 9
# Test the formula approach
numbers = [9625, 123, 999, 38, 0]
for num in numbers:
result = digital_root_formula(num)
print(f"Digital root of {num}: {result}")
Digital root of 9625: 4 Digital root of 123: 6 Digital root of 999: 9 Digital root of 38: 2 Digital root of 0: 0
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive | O(log n) | O(log n) | Understanding the process |
| Iterative | O(log n) | O(1) | Memory efficiency |
| Formula | O(1) | O(1) | Performance |
Conclusion
The digital root can be found through repeated digit summation or using the mathematical formula 1 + (n-1) % 9. The formula approach is most efficient with O(1) time complexity.
Advertisements
