a ccept number from user and calculate the sum of all number from 1 to given number
Answers
Input: n = 5
Output: Sum of digits in numbers from 1 to 5 = 15
Input: n = 12
Output: Sum of digits in numbers from 1 to 12 = 51
Input: n = 328
Output: Sum of digits in numbers from 1 to 328 = 3241
Naive Solution:
A naive solution is to go through every number x from 1 to n and compute the sum in x by traversing all digits of x. Below is the implementation of this idea.
# 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))
Output:
Sum of digits in numbers from 1 to 328 is 3241
please mark my ANSWER as brainliest . it is my humble request