Print Sum of all digits in Numbers From 1 to N in Python

Modest programs can become severely difficult if the programmer itself does not understand the problem statement. So getting clarification of the problem statement is extremely necessary before you begin solving that problem. Now during competitions, interview rounds, etc, the problem statement itself is very confusing. One of the very simplest yet confusing problem statements we found is of performing addition. Well as simple as it sounds the complex it is. So today we’re going to find out how to Print Sum of all digits in Numbers From 1 to N in Python

 

What’s The Approach?

 

  • One of the simplest approaches we can use is to traverse all the numbers from 1 to N. And for each number we can compute the sum of its digits.

 

  • We will perform modulo operation x % 10 for each number from 1 to N so that we get individual digits of each number eventually added up in the sum variable.

 

  • After the above instruction gets executed successfully, we will do x = x // 10. So that we know when to stop.

 

  • The above instructions will keep executing till x != 0  remains true.

 

Also Read: Check If Two Strings Are Anagram in Python

 

Python Program To Print Sum of All Digits in Numbers From 1 to N

 

Input:

n = 328

 

Output:

 

Sum of digits in numbers from 1 to 328 is 3241

 

# A Simple Python program to compute sum
# of digits in numbers from 1 to n

# Returns sum of all digits in numbers
# from 1 to n
def sumOfDigitsFrom1ToN(n) :

    result = 0 # initialize result

    # One by one compute sum of digits
    # in every number from 1 to n
    for x in range(1, n+1) :
        result = result + sumOfDigits(x)

    return result

# A utility function to compute sum of
# digits in a given number x
def sumOfDigits(x) :
    sum = 0
    while (x != 0) :
        sum = sum + x % 10
        x = x // 10
    
    return sum


# Driver Program
n = 328
print("Sum of digits in numbers from 1 to", n, "is", sumOfDigitsFrom1ToN(n))


 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *