# Count of numbers satisfying m + sum(m) + sum(sum(m)) = N in C++

C++Server Side ProgrammingProgramming

Given a number N as input. The goal is to find numbers m upto N that satisfy the following condition. Here N<=109

m + sum(m) + sum ( sum (m) ) = N. Where sum(m) is the sum of digits of m.

If m is 137 then sum(m)=1+3+7=11 and sum(sum(m))= sum(11)= 1+1=2

## Let us understand with examples.

For Example

Input - N=27

Output - Count of numbers satisfying m + sum(m) + sum(sum(m)) = N are: 3

Explanation - The numbers are:

9 ( 9 + 9 + 9 = 27 )

15 ( 15 + (1+5) + (6) = 27 )

21 ( 21 + (2+1) + (3) = 27 )

Input - N=81

Output - Count of numbers satisfying m + sum(m) + sum(sum(m)) = N are: 2

Explanation - The numbers are:

63 ( 63 + (6+3) + 9 = 81 )

66 ( 66 + (6+6) + (1+2) = 81 )

## Approach used in the below program is as follows

In this approach we will calculate sums of digits of numbers and compare the added sums with N. If the calculated sum is equal to N then increment count. At the end return count as result.

As largest number could be 10then maximum sum of digits of m can be 81 ( 9*9 ) and the next maximum sum of digits for sum(sum(m)) can be 16 ( 7+9 for 79 ). So we will check for numbers from N-97 to N as integers smaller than N-97 and greater than N will not satisfy the given condition.

• Take integer N as input.
• Function total(int num) takes a number total and returns the sum of its digits.
• Take res_total as the sum of digits and res as current remainder. Initialize both with 0.
• Traverse each unit digit using a while loop.
• Take the unit digit as res=num % 10 and add to res_total.
• Reduce num by 10 for next digit.
• Return res_total as sum of digits of num at the end.
• Function condition(int N) takes N and returns the count of  numbers satisfying m + sum(m) + sum(sum(m)).
• Take the initial count as 0.
• Traverse using for loop from i=N-97 to i<=N.
• Calculate sum of digits as temp_1=total(i).
• Calculate sum of digits of total(i) as total(temp_1).
• Set temp_3 = i + temp_1 + temp_2. If it is equal to N then increment count.
• At the end of for loop return count as result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int total(int num) {
int res_total = 0;
int res = 0;
while (num > 0) {
res = num % 10;
res_total = res_total + res;
num = num / 10;
}
return res_total;
}
int condition(int N) {
int count = 0;
for (int i = N - 97; i <= N; i++) {
int temp_1 = total(i);
int temp_2 = total(temp_1);
int temp_3 = i + temp_1 + temp_2;
if (temp_3 == N) {
count++;
}
}
return count;
}
int main() {
int N = 9999;
cout << "Count of numbers satisfying m + sum(m) + sum(sum(m)) = N are: " << condition(N);
return 0;
}

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

## Output

Count of numbers satisfying m + sum(m) + sum(sum(m)) = N are: 2
Updated on 29-Jan-2021 08:12:54