Ruby Program for Sum of Digits Using Recursion
def sum_of_digits(n); return n if n < 10; n % 10 + sum_of_digits(n / 10); end.Examples
How to Think About It
% operator to get the last digit and / to remove it. Then add the last digit to the sum of digits of the remaining number. Stop when the number is less than 10 because then it is a single digit.Algorithm
Code
def sum_of_digits(n) return n if n < 10 n % 10 + sum_of_digits(n / 10) end puts sum_of_digits(1234)
Dry Run
Let's trace sum_of_digits(1234) through the code
Initial call
n = 1234, n >= 10, so calculate 1234 % 10 = 4 and call sum_of_digits(1234 / 10 = 123)
Second call
n = 123, n >= 10, calculate 123 % 10 = 3 and call sum_of_digits(123 / 10 = 12)
Third call
n = 12, n >= 10, calculate 12 % 10 = 2 and call sum_of_digits(12 / 10 = 1)
Base case
n = 1, n < 10, return 1
Return and sum up
Return 1 to previous call, sum 2 + 1 = 3, then 3 + 3 = 6, then 4 + 6 = 10
| Call | n | Last Digit (n % 10) | Remaining Number (n / 10) | Return Value |
|---|---|---|---|---|
| 1 | 1234 | 4 | 123 | 4 + sum_of_digits(123) |
| 2 | 123 | 3 | 12 | 3 + sum_of_digits(12) |
| 3 | 12 | 2 | 1 | 2 + sum_of_digits(1) |
| 4 | 1 | 1 | 0 | 1 |
Why This Works
Step 1: Base case stops recursion
When the number is less than 10, return n stops the recursion because a single digit's sum is itself.
Step 2: Extract last digit
Using n % 10 gets the last digit of the number to add to the sum.
Step 3: Recursive call reduces problem size
Calling sum_of_digits(n / 10) removes the last digit and repeats the process on the smaller number.
Step 4: Sum builds up on return
Each recursive call returns the sum of digits so far, adding the last digit until the full sum is computed.
Alternative Approaches
def sum_of_digits_iterative(n) sum = 0 while n > 0 sum += n % 10 n /= 10 end sum end puts sum_of_digits_iterative(1234)
def sum_of_digits_string(n) n.to_s.chars.map(&:to_i).sum end puts sum_of_digits_string(1234)
Complexity: O(log n) time, O(log n) space
Time Complexity
The function processes one digit per recursive call, so the number of calls is proportional to the number of digits, which is log base 10 of n.
Space Complexity
Each recursive call adds a layer to the call stack, so space used is proportional to the number of digits, O(log n).
Which Approach is Fastest?
The iterative approach uses constant space O(1) and is generally faster due to no recursion overhead, but recursion is elegant and easy to understand.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(log n) | O(log n) | Learning recursion and elegant code |
| Iterative | O(log n) | O(1) | Performance and large inputs |
| String conversion | O(log n) | O(log n) | Simple code for small inputs |