# Count numbers with difference between number and its digit sum greater than specific value in C++

C++Server Side ProgrammingProgramming

We are provided two numbers N which defines a range [1,N] and D which is a difference.The goal is to find all the numbers in the range [1,N] such that the [ number - (sum of its digits) ] > D. We will do this by traversing numbers from 1 to N and for each number we will calculate its digit sum using a while loop. Check if the number and calculated digit sum has a difference more than D.

Let’s understand with examples.

Input

N=15 D=5

Output

Numbers such that difference b/w no. and its digit sum greater than value D: 6

Explanation

Numbers 10, 11, 12, 13, 14, 15 satisfy the condition. ( 10-1, 11-2, 12-3, 13-4, 14-5, 15-6 ) all differences are 9 which is greater than 5.

Input

N=20 D=10

Output

Only 20 satisfies the condition. 20-2=18 > 10.

Explanation

This is list of numbers divisible by all non-zero digits : 100 101 102 104 105 110 111 112 115 120 122 124 126 128 132 135 140 144 150 155 162 168 175 184 200

## Approach used in the below program is as follows

• We take integers N and D.

• Function digitSum(int n, int d) takes variables N, D and returns the count of numbers with (num-digitsum) >d.

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

• Take variable digsum as 0

• Traverse range of numbers using for loop. i=1 to i=n

• 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 ( i - 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 n, int d){
int count = 0;
int digsum = 0;
for (int i = 1; i <= n; i++){
int num=i;
digsum=0;
while(num>0){
digsum+=num%10; //sum of digits
num=num/10;
}
if(i-digsum>d) //original number is i {
count++;
//cout<<i<<" ";
}
}
return count;
}
int main(){
int N = 20;
int D = 8;
cout <<"Numbers such that difference between number and its digit sum greater than specific value: "<<digitSum(N,D);
return 0;
}

## Output

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

Numbers such that difference between number and its digit sum greater than specific value: 11
Published on 31-Oct-2020 04:51:57