Write a program to recursively sum the individual digits to obtain a single digit using Python

Posted by Rajnilari2015 under Python category on | Points: 40 | Views : 765
Let's say, we have a number as N=123456789

If we sum them the result will be 1+2+3+4+5+6+7+8+9 =45 . If we further sum them it will be 4+5 = 9, which is a single digit.

How can we do so? The below is the program that will help us

from System import *

class Program(object):
def Main(args):

Main = staticmethod(Main)

def FindSingleDigit(N):
sum = 0
while N != 0:
sum = sum + (N % 10)
N = N / 10
return Program.FindSingleDigit(sum) if sum >= 10 else sum

FindSingleDigit = staticmethod(FindSingleDigit)

Let us understand the program first

while N != 0:
sum = sum + (N % 10)
N = N / 10

The loop continues till the value of "N" becomes zero and it gives the total sum of the individual digits. Then it comes out of the loop. Next we perform a checking if the sum obtained is greater than or equals to 10 which is a two digit. In that case , then program makes a recursive call. If it is a single digit, then that value gets return.

Let us analyze the program with out example.

Pass 1: sum = 45
Pass 2: sum = 9

Comments or Responses

Login to post response