Count of numbers from range[L, R] whose sum of digits is Y in C++

C++Server Side ProgrammingProgramming

We are provided two numbers START and END to define a range of numbers.The goal is to find all the numbers in the range [START,END] which have sum of digits equal to a given number Y.

We will do this by traversing numbers from START to END and for each number we will count the sum of its digit using a while loop. If this sum is equal to Y, increment count.

Let’s understand with examples.

Input 

START=10 END=20 Y=4

Output 

Numbers such that digit sum is equal to Y: 1

Explanation 

Number 13 has digit sum equal to 4.

Input 

START=10 END=50 Y=5

Output 

Numbers such that digit sum is equal to Y: 5

Explanation 

Numbers 14, 23, 32, 41 and 50 have digit sum 5.

Approach used in the below program is as follows

  • We take integers START, END, Y.

  • Function digitSum(int start, int end, int y) returns the count of numbers with digitsum=y

  • Take the initial variable count as 0 for such numbers.

  • Take variable digsum as 0

  • Traverse range of numbers using for loop. i=start to i=end

  • Now for each number num=i, using while loop check if number is >0.

  • calculate digsum+=num%10. Reduce num=num/10 to add the next digit.

  • At the end of the while, check if ( digsum == d ). If true increment count.

  • At the end of all loops count will have a total number which satisfies the condition.

  • Return the count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int digitSum(int start, int end, int y){
   int count = 0;
   int digsum = 0;
   for (int i = start; i <= end; i++){
      int num=i;
      digsum=0;
      while(num>0){
         digsum+=num%10; //sum of digits
         num=num/10;
      }
      if(digsum==y) //original number is i{
         count++;
         //cout<<i<<" ";
      }
   }
   return count;
}
int main(){
   int START = 100;
   int END = 1000;
   int Y = 5;
   cout <<"Numbers such that digit sum is equal to Y: "<<digitSum(START,END,Y);
   return 0;
}

Output

If we run the above code it will generate the following output −

Numbers such that digit sum is equal to Y: 15
raja
Published on 31-Oct-2020 04:56:13
Advertisements