Find a Number X whose sum with its digits is equal to N
Last Updated :
15 Nov, 2023
Given a positive number N. We need to find number(s) such that sum of digits of those numbers to themselves is equal to N. If no such number is possible print -1. Here N \in [1, 1000000000]
Examples:
Input : N = 21
Output : X = 15
Explanation : X + its digit sum
= 15 + 1 + 5
= 21
Input : N = 5
Output : -1
Input : N = 100000001
Output : X = 99999937
X = 100000000
Method 1 : (Naive Approach)
We have already discussed the approach here. The approach might not work for N as large as 10^9
.
Method 2 : (Efficient)
It is a fact that for a number X < = 1000000000, the sum of digits never exceeds 100. Using this piece of information, we can iterate over all possibilities in the range 0 to 100 on both the sides of the number and check if the number X is equal to N - sum of digits of X. All the possibilities will be covered in this range.
C++
// CPP program to find x such that
// X + sumOfDigits(X) = N
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
// Computing the sum of digits of x
int sumOfDigits(long int x)
{
int sum = 0;
while (x > 0) {
sum += x % 10;
x /= 10;
}
return sum;
}
// Checks for 100 numbers on both left
// and right side of the given number to
// find such numbers X such that X +
// sumOfDigits(X) = N and updates the answer
// vector accordingly
void compute(vector<long int>& answer, long int n)
{
// Checking for all possibilities of
// the answer
for (int i = 0; i <= 100; i++) {
// Evaluating the value on the left
// side of the given number
long int valueOnLeft = abs(n - i) +
sumOfDigits(abs(n - i));
// Evaluating the value on the right
// side of the given number
long int valueOnRight = n + i + sumOfDigits(n + i);
// Checking the condition of equality
// on both sides of the given number N
// and updating the answer vector
if (valueOnLeft == n)
answer.push_back(abs(n - i));
if (valueOnRight == n)
answer.push_back(n + i);
}
}
// Driver Function
int main()
{
long int N = 100000001;
vector<long int> answer;
compute(answer, N);
// If no solution exists, print -1
if (answer.size() == 0)
cout << -1;
else {
// If one or more solutions are possible,
// printing them!
for (auto it = answer.begin(); it != answer.end(); ++it)
cout << "X = " << (*it) << endl;
}
return 0;
}
Java
// Java program to find x such that
// X + sumOfDigits(X) = N
import java.util.*;
import java.lang.*;
import java.io.*;
class GeeksforGeeks {
// Computing the sum of digits of x
static int sumOfDigits(long x)
{
int sum = 0;
while (x > 0) {
sum += (x % 10);
x /= 10;
}
return sum;
}
// Checks for 100 numbers on both left
// and right side of the given number to
// find such numbers X such that
// X + sumOfDigits(X) = N and prints solution.
static void compute(long n)
{
long answer[] = new long[100];
int pos = 0;
// Checking for all possibilities of the answer
// in the given range
for (int i = 0; i <= 100; i++) {
// Evaluating the value on the left side of the
// given number
long valueOnLeft = Math.abs(n - i) +
sumOfDigits(Math.abs(n - i));
// Evaluating the value on the right side of the
// given number
long valueOnRight = (n + i) + sumOfDigits(n + i);
if (valueOnRight == n)
answer[pos++] = (n + i);
if (valueOnLeft == n)
answer[pos++] = Math.abs(n - i);
}
if (pos == 0)
System.out.print(-1);
else
for (int i = 0; i < pos; i++)
System.out.println("X = " + answer[i]);
}
// Driver Function
public static void main(String[] args)
{
long N = 100000001;
compute(N);
}
}
Python3
# Python3 program to find x such that
# X + sumOfDigits(X) = N
# Computing the sum of digits of x
def sumOfDigits(x):
sum = 0;
while (x > 0):
sum += (x % 10);
x = int(x / 10);
return sum;
# Checks for 100 numbers on both left
# and right side of the given number
# to find such numbers X such that
# X + sumOfDigits(X) = N and prints
# solution.
def compute(n):
answer = [];
pos = 0;
# Checking for all possibilities
# of the answer in the given range
for i in range(101):
# Evaluating the value on the
# left side of the given number
valueOnLeft = (abs(n - i) +
sumOfDigits(abs(n - i)));
# Evaluating the value on the right
# side of the given number
valueOnRight = (n + i) + sumOfDigits(n + i);
if (valueOnRight == n):
answer.append(n + i);
if (valueOnLeft == n):
answer.append(abs(n - i));
if (len(answer)== 0):
print(-1);
else:
for i in range(len(answer)):
print("X =", answer[i]);
# Driver Code
N = 100000001;
compute(N);
# This code is contributed
# by mits
C#
// C# program to find x such that
// X + sumOfDigits(X) = N
using System;
public class GFG{
// Computing the sum of digits of x
static int sumOfDigits(long x)
{
int sum = 0;
while (x > 0) {
sum += (int)(x % 10);
x /= 10;
}
return sum;
}
// Checks for 100 numbers on both left
// and right side of the given number to
// find such numbers X such that
// X + sumOfDigits(X) = N and prints solution.
static void compute(long n)
{
long []answer = new long[100];
int pos = 0;
// Checking for all possibilities of the answer
// in the given range
for (int i = 0; i <= 100; i++) {
// Evaluating the value on the left side of the
// given number
long valueOnLeft = Math.Abs(n - i) +
sumOfDigits(Math.Abs(n - i));
// Evaluating the value on the right side of the
// given number
long valueOnRight = (n + i) + sumOfDigits(n + i);
if (valueOnRight == n)
answer[pos++] = (n + i);
if (valueOnLeft == n)
answer[pos++] = Math.Abs(n - i);
}
if (pos == 0)
Console.Write(-1);
else
for (int i = 0; i < pos; i++)
Console.WriteLine("X = " + answer[i]);
}
// Driver Function
static public void Main (){
long N = 100000001;
compute(N);
}
}
JavaScript
<script>
// JavaScript program to find x such that
// X + sumOfDigits(X) = N
// Computing the sum of digits of x
function sumOfDigits(x)
{
let sum = 0;
while (x > 0)
{
sum += (x % 10);
x = Math.floor(x / 10);
}
return sum;
}
// Checks for 100 numbers on both left
// and right side of the given number to
// find such numbers X such that
// X + sumOfDigits(X) = N and prints solution.
function compute(n)
{
let answer = [];
let pos = 0;
// Checking for all possibilities
// of the answer in the given range
for(let i = 0; i <= 100; i++)
{
// Evaluating the value on the
// left side of the given number
let valueOnLeft = Math.abs(n - i) +
sumOfDigits(Math.abs(n - i));
// Evaluating the value on the right
// side of the given number
let valueOnRight = (n + i) +
sumOfDigits(n + i);
// Checking the condition of equality
// on both sides of the given number N
// and updating the answer vector
if (valueOnRight == n)
answer[pos++] = (n + i);
if (valueOnLeft == n)
answer[pos++] = Math.abs(n - i);
}
if (pos == 0)
document.write(-1);
else
for(let i = 0; i < pos; i++)
document.write("X = " + answer[i] + "<br/>");
}
// Driver Code
let N = 100000001;
compute(N);
// This code is contributed by susmitakundugoaldanga
</script>
PHP
<?php
// PHP program to find x such that
// X + sumOfDigits(X) = N
// Computing the sum of digits of x
function sumOfDigits($x)
{
$sum = 0;
while ($x > 0)
{
$sum += ($x % 10);
$x = (int)$x / 10;
}
return $sum;
}
// Checks for 100 numbers on both left
// and right side of the given number
// to find such numbers X such that
// X + sumOfDigits(X) = N and prints
// solution.
function compute($n)
{
$answer = array(0);
$pos = 0;
// Checking for all possibilities
// of the answer in the given range
for ($i = 0; $i <= 100; $i++)
{
// Evaluating the value on the
// left side of the given number
$valueOnLeft = abs($n - $i) +
sumOfDigits(abs($n - $i));
// Evaluating the value on the right
// side of the given number
$valueOnRight = ($n + $i) + sumOfDigits($n + $i);
if ($valueOnRight == $n)
$answer[$pos++] = ($n + $i);
if ($valueOnLeft == $n)
$answer[$pos++] =abs($n - $i);
}
if ($pos == 0)
echo (-1),"\n";
else
for ($i = 0; $i < $pos; $i++)
echo "X = ", $answer[$i], "\n";
}
// Driver Code
$N = 100000001;
compute($N);
// This code is contributed
// by Sach_Code
?>
Output:
X = 100000000
X = 99999937
The maximum complexity of this approach can be O(100*len)
where len is the number of digits in the number max(len) = 9. Thus the complexity can almost be said to be O(len)
Approach#2: Using binary search
this approach to solve this problem is to use binary search. We can start with the middle value between 1 and N, and then we can check if the sum of this number and its digit sum is equal to N. If it is not, we can use binary search to find a number that satisfies the condition.
Algorithm
1. Define a function "find_number_with_digit_sum" that takes an integer "N" as input.
2. Define a function "check_number_with_digit_sum" that takes a number "X" and an integer "N" as input, and checks if the sum of "X" and its digit sum is equal to "N". Return True if the condition is satisfied, False otherwise.
3. Set "low" to 1 and "high" to N.
4. While "low" is less than or equal to "high":
a. Calculate the middle value "mid" between "low" and "high".
b. If "check_number_with_digit_sum(mid, N)" returns True, return "mid".
c. If "mid" plus its digit sum is less than "N", set "low" to "mid" + 1.
d. Otherwise, set "high" to "mid" - 1.
5. If no number was found, return -1.
C++
#include <iostream>
using namespace std;
// Function to calculate the sum of the digits of a number
int digit_sum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10; // Add the last digit of n to the sum
n /= 10; // Remove the last digit of n
}
return sum;
}
// Function to check if a number X has the desired digit sum N
bool check_number_with_digit_sum(int X, int N) {
return X + digit_sum(X) == N; // Return true if X + its digit sum equals N
}
// Function to find the smallest number that has the desired digit sum N
int find_number_with_digit_sum(int N) {
int low = 1, high = N; // Set the search range to [1, N]
while (low <= high) { // Perform binary search until the range is empty
int mid = (low + high) / 2; // Calculate the midpoint of the range
if (check_number_with_digit_sum(mid, N)) { // Check if the midpoint has the desired digit sum
return mid; // Return the midpoint if it does
}
else if (mid + digit_sum(mid) < N) { // If the midpoint has a digit sum less than N
low = mid + 1; // Search the upper half of the range
}
else { // If the midpoint has a digit sum greater than or equal to N
high = mid - 1; // Search the lower half of the range
}
}
return -1; // If no number with the desired digit sum is found, return -1
}
int main() {
int N = 100000001; // Choose a desired digit sum
cout << find_number_with_digit_sum(N) << endl; // Find the smallest number with that digit sum and output it
return 0;
}
Java
public class Main {
// Function to calculate the sum of the digits of a number
static int digitSum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10; // Add the last digit of n to the sum
n /= 10; // Remove the last digit of n
}
return sum;
}
// Function to check if a number X has the desired digit sum N
static boolean checkNumberWithDigitSum(int X, int N) {
return X + digitSum(X) == N; // Return true if X + its digit sum equals N
}
// Function to find the smallest number that has the desired digit sum N
static int findNumberWithDigitSum(int N) {
int low = 1, high = N; // Set the search range to [1, N]
while (low <= high) { // Perform binary search until the range is empty
int mid = (low + high) / 2; // Calculate the midpoint of the range
if (checkNumberWithDigitSum(mid, N)) { // Check if the midpoint has the desired digit sum
return mid; // Return the midpoint if it does
} else if (mid + digitSum(mid) < N) { // If the midpoint has a digit sum less than N
low = mid + 1; // Search the upper half of the range
} else { // If the midpoint has a digit sum greater than or equal to N
high = mid - 1; // Search the lower half of the range
}
}
return -1; // If no number with the desired digit sum is found, return -1
}
public static void main(String[] args) {
int N = 100000001; // Choose a desired digit sum
System.out.println(findNumberWithDigitSum(N)); // Find the smallest number with that digit sum and output it
}
}
Python3
def digit_sum(n):
sum = 0
while n > 0:
sum += n % 10
n //= 10
return sum
def check_number_with_digit_sum(X, N):
return X + digit_sum(X) == N
def find_number_with_digit_sum(N):
low, high = 1, N
while low <= high:
mid = (low + high) // 2
if check_number_with_digit_sum(mid, N):
return mid
elif mid + digit_sum(mid) < N:
low = mid + 1
else:
high = mid - 1
return -1
N = 100000001
print(find_number_with_digit_sum(N))
C#
using System;
class Program
{
// Function to calculate the sum of the digits of a number
static int DigitSum(int n)
{
int sum = 0;
while (n > 0)
{
sum += n % 10; // Add the last digit of n to the sum
n /= 10; // Remove the last digit of n
}
return sum;
}
// Function to check if a number X has the desired digit sum N
static bool CheckNumberWithDigitSum(int X, int N)
{
return X + DigitSum(X) == N; // Return true if X + its digit sum equals N
}
// Function to find the smallest number that has the desired digit sum N
static int FindNumberWithDigitSum(int N)
{
int low = 1, high = N; // Set the search range to [1, N]
while (low <= high)
{
int mid = (low + high) / 2; // Calculate the midpoint of the range
if (CheckNumberWithDigitSum(mid, N)) // Check if the midpoint has the desired digit sum
{
return mid; // Return the midpoint if it does
}
else if (mid + DigitSum(mid) < N) // If the midpoint has a digit sum less than N
{
low = mid + 1; // Search the upper half of the range
}
else // If the midpoint has a digit sum greater than or equal to N
{
high = mid - 1; // Search the lower half of the range
}
}
return -1; // If no number with the desired digit sum is found, return -1
}
static void Main()
{
int N = 100000001; // Choose a desired digit sum
Console.WriteLine(FindNumberWithDigitSum(N)); // Find the smallest number with that digit sum and output it
}
}
JavaScript
// Function to calculate the sum of the digits of a number
function digitSum(n) {
let sum = 0;
while (n > 0) {
sum += n % 10; // Add the last digit of n to the sum
n = Math.floor(n / 10); // Remove the last digit of n
}
return sum;
}
// Function to check if a number X has the desired digit sum N
function checkNumberWithDigitSum(X, N) {
return X + digitSum(X) === N; // Return true if X + its digit sum equals N
}
// Function to find the smallest number that has the desired digit sum N
function findNumberWithDigitSum(N) {
let low = 1;
let high = N; // Set the search range to [1, N]
while (low <= high) {
// Perform binary search until the range is empty
let mid = Math.floor((low + high) / 2); // Calculate the midpoint of the range
if (checkNumberWithDigitSum(mid, N)) {
// Check if the midpoint has the desired digit sum
return mid; // Return the midpoint if it does
} else if (mid + digitSum(mid) < N) {
// If the midpoint has a digit sum less than N
low = mid + 1; // Search the upper half of the range
} else {
// If the midpoint has a digit sum greater than or equal to N
high = mid - 1; // Search the lower half of the range
}
}
return -1; // If no number with the desired digit sum is found, return -1
}
const N = 100000001; // Choose a desired digit sum
console.log(findNumberWithDigitSum(N)); // Find the smallest number with that digit sum and output it
Time Complexity: O(log10(N) * log10(X)), where X is the answer.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem