# Find a Number X whose sum with its digits is equal to N in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to find a number whose some including with its digits is equal to the given number N.

The idea is simple, we are going to check the left and right 100 numbers of the given number. It won't lie out that bound as N ≤ 1000000000 and the sum won't exceed 100.

Let's see the steps to solve the problem.

• Initialize the number.

• Write a loop that iterates 100 times.

• Get the n - i and n + i values.

• Find the sum of the digits and add them.

• If anyone of them is equal to the N, print them.

## Example

Let's see the code.

Live Demo

#include <bits/stdc++.h>
using namespace std;
int digitsSum(int n) {
int sum = 0;
while (n) {
sum += n % 10;
n /= 10;
}
return sum;
}
void findX(long int n) {
bool is_found = false;
for (int i = 0; i <= 100; i++) {
long int valueOnLeft = abs(n - i) + digitsSum(abs(n - i));
long int valueOnRight = n + i + digitsSum(n + i);
if (valueOnLeft == n) {
is_found = true;
cout << abs(n - i) << " ";
}
if (valueOnRight == n) {
is_found = true;
cout << (n + i) << " ";
}
}
if (!is_found) {
cout << "No numbers found";
}
cout << endl;
}
int main() {
int n = 89;
findX(n);
return 0;
}

## Output

If you execute the above program, then you will get the following result.

76

## Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Published on 01-Feb-2021 11:51:34