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
Selected Reading
Compute sum of digits in all numbers from 1 to n
In this problem, we have to find the sum of digits of all numbers in range 1 to n. For an example the sum of digits of 54 is 5 + 4 = 9, Like this, we have to find all the numbers and their sum of digits.
We know that there are 10d - 1 numbers can be generated, whose number of digits is d. To find the sum of all those numbers of digit d, we can use a recursive formula.
sum(10d- 1)=sum(10d-1- 1)*10+45*(10d-1)
Input and Output
Input: This algorithm takes the upper limit of the range, say it is 20. Output: Sum of digits in all numbers from 1 to n. Here the result is 102
Algorithm
digitSumInRange(n)
Input: The upper limit of the range.
Output − the sum of digits for all number in the range (1-n).
Begin if nExample
#include#include using namespace std; int digitSumInRange(int n) { if (n> n; cout Output
Enter upper limit of the range: 20 Sum of digits in range (1 to 20) is: 102
Advertisements
