- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures

- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces

# Find a number x such that sum of x and its digits is equal to given n using C++.

Here we will see one problem, where we take a number n, we have to find another value say x, such that x + digit sum of x is same as the given number n. Suppose the value of n is 21. This program will return a number x = 15, as 15 + digit sum of 15, i.e. 15 + 1 + 5 = 21 = n.

To solve this problem, we have to follow simple approach. We will iterate through 1 to n, in each iteration, we will see if the sum of the number and its digit sum is same as the number, then stop, otherwise continue.

## Example

#include<iostream> using namespace std; int getDigitSum(int n) { int sum = 0; while (n) { sum += n % 10; n /= 10; } return sum; } int getNumber(int n) { for (int i = 0; i <= n; i++) if (i + getDigitSum(i) == n) return i; return -1; } int main() { int n = 21; cout << "The value of x is: " << getNumber(n); }

## Output

The value of x is: 15

- Related Articles
- Find a number x such that sum of x and its digits is equal to given n in C++
- Find a Number X whose sum with its digits is equal to N in C++
- If $\overline{98125x2}$ is a number with $x$ as its tens digits such that it is divisible by 4. Find all the possible values of $x$.
- Find the minimum positive integer such that it is divisible by A and sum of its digits is equal to B in Python
- Find minimum x such that (x % k) * (x / k) == n in C++
- Find the value of k such that the polynomial $x^{2}-(k+6)x+2(2k-1)$ has sum of its zeros equal to half of their product.
- Find maximum value of x such that n! % (k^x) = 0 in C++
- Find the Number of Solutions of n = x + n x using C++
- Find maximum N such that the sum of square of first N natural numbers is not more than X in Python
- Find maximum N such that the sum of square of first N natural numbers is not more than X in C++
- Find smallest number with given number of digits and sum of digits in C++
- Find number of pairs (x, y) in an array such that x^y > y^x in C++
- A two digit number is 4 times the sum of its digits and twice the product of its digits. Find the number.
- Print a number strictly less than a given number such that all its digits are distinct in C++
- Find a distinct pair (x, y) in given range such that x divides y in C++

Advertisements