Smallest number greater than Y with sum of digits equal to X
Last Updated :
10 Jun, 2021
Given two integers X and Y, find the minimal number with the sum of digits X, which is strictly greater than Y.
Examples:
Input: X = 18, Y = 99
Output: 189
Explanation:
189 is the smallest number greater than 99 having sum of digits = 18.
Input: X = 12, Y = 72
Output: 75
Explanation:
75 is the smallest number greater than 72 that has sum of digits = 12.
Naive Approach: The naive approach is iterate from Y + 1 and check if any number whose sum of digits is X or not. If we found any such number then print that number.
Time Complexity: O((R - Y)*log10N), where R is the maximum number till where we iterate and N is the number in the range [Y, R]
Auxiliary Space: O(1)
Efficient Approach: The idea is to iterate through the digits of Y from right to left, and try to increase the current digit and change the digits to the right in order to make the sum of digits equal to X. Below are the steps:
- If we are considering the (k + 1)th digit from the right and increasing it, then it is possible to make the sum of k least significant digits to be any number in the range [0, 9k].
- When such a position is found, then stop the process and print the number at that iteration.
- If k least significant digits have sum M (where 0 ? M ? 9k), then obtain the answer greedily:
- Traverse from the right to the left and insert 9 and subtract 9 from the sum of digits.
- Once, the sum is less than 9, place the remaining sum.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the minimum string
// of length d having the sum of digits s
string helper(int d, int s)
{
// Return a string of length d
string ans(d, '0');
for (int i = d - 1; i >= 0; i--) {
// Greedily put 9's in the end
if (s >= 9) {
ans[i] = '9';
s -= 9;
}
// Put remaining sum
else {
char c = (char)s + '0';
ans[i] = c;
s = 0;
}
}
return ans;
}
// Function to find the smallest
// number greater than Y
// whose sum of digits is X
string findMin(int x, int Y)
{
// Convert number y to string
string y = to_string(Y);
int n = y.size();
vector<int> p(n);
// Maintain prefix sum of digits
for (int i = 0; i < n; i++) {
p[i] = y[i] - '0';
if (i > 0)
p[i] += p[i - 1];
}
// Iterate over Y from the back where
// k is current length of suffix
for (int i = n - 1, k = 0;; i--, k++) {
// Stores current digit
int d = 0;
if (i >= 0)
d = y[i] - '0';
// Increase current digit
for (int j = d + 1; j <= 9; j++) {
// Sum upto current prefix
int r = (i > 0) * p[i - 1] + j;
// Return answer if remaining
// sum can be obtained in suffix
if (x - r >= 0 and x - r <= 9 * k) {
// Find suffix of length k
// having sum of digits x-r
string suf = helper(k, x - r);
string pre = "";
if (i > 0)
pre = y.substr(0, i);
// Append current character
char cur = (char)j + '0';
pre += cur;
// Return the result
return pre + suf;
}
}
}
}
// Driver Code
int main()
{
// Given Number and Sum
int x = 18;
int y = 99;
// Function Call
cout << findMin(x, y) << endl;
return 0;
}
Java
// Java program for the above approach
import java.util.*;
@SuppressWarnings("unchecked")
class GFG{
// Function to return the minimum String
// of length d having the sum of digits s
static String helper(int d, int s)
{
// Return a String of length d
StringBuilder ans = new StringBuilder();
for(int i = 0; i < d; i++)
{
ans.append("0");
}
for(int i = d - 1; i >= 0; i--)
{
// Greedily put 9's in the end
if (s >= 9)
{
ans.setCharAt(i,'9');
s -= 9;
}
// Put remaining sum
else
{
char c = (char)(s + (int)'0');
ans.setCharAt(i, c);
s = 0;
}
}
return ans.toString();
}
// Function to find the smallest
// number greater than Y
// whose sum of digits is X
static String findMin(int x, int Y)
{
// Convert number y to String
String y = Integer.toString(Y);
int n = y.length();
ArrayList p = new ArrayList();
for(int i = 0; i < n; i++)
{
p.add(0);
}
// Maintain prefix sum of digits
for(int i = 0; i < n; i++)
{
p.add(i, (int)((int) y.charAt(i) - (int)'0'));
if (i > 0)
{
p.add(i, (int)p.get(i) +
(int)p.get(i - 1));
}
}
// Iterate over Y from the back where
// k is current length of suffix
for(int i = n - 1, k = 0;; i--, k++)
{
// Stores current digit
int d = 0;
if (i >= 0)
{
d = (int) y.charAt(i) - (int)'0';
}
// Increase current digit
for(int j = d + 1; j <= 9; j++)
{
int r = j;
// Sum upto current prefix
if (i > 0)
{
r += (int) p.get(i - 1);
}
// Return answer if remaining
// sum can be obtained in suffix
if (x - r >= 0 && x - r <= 9 * k)
{
// Find suffix of length k
// having sum of digits x-r
String suf = helper(k, x - r);
String pre = "";
if (i > 0)
pre = y.substring(0, i);
// Append current character
char cur = (char)(j + (int)'0');
pre += cur;
// Return the result
return pre + suf;
}
}
}
}
// Driver code
public static void main(String[] arg)
{
// Given number and sum
int x = 18;
int y = 99;
// Function call
System.out.print(findMin(x, y));
}
}
// This code is contributed by pratham76
Python3
# Python3 program for the
# above approach
# Function to return the
# minimum string of length
# d having the sum of digits s
def helper(d, s):
# Return a string of
# length d
ans = ['0'] * d
for i in range(d - 1,
-1, -1):
# Greedily put 9's
# in the end
if (s >= 9):
ans[i] = '9'
s -= 9
# Put remaining sum
else:
c = chr(s +
ord('0'))
ans[i] = c;
s = 0;
return ''.join(ans);
# Function to find the
# smallest number greater
# than Y whose sum of
# digits is X
def findMin(x, Y):
# Convert number y
# to string
y = str(Y);
n = len(y)
p = [0] * n
# Maintain prefix sum
# of digits
for i in range(n):
p[i] = (ord(y[i]) -
ord('0'))
if (i > 0):
p[i] += p[i - 1];
# Iterate over Y from the
# back where k is current
# length of suffix
n - 1
k = 0
while True:
# Stores current digit
d = 0;
if (i >= 0):
d = (ord(y[i]) -
ord('0'))
# Increase current
# digit
for j in range(d + 1,
10):
# Sum upto current
# prefix
r = ((i > 0) *
p[i - 1] + j);
# Return answer if
# remaining sum can
# be obtained in suffix
if (x - r >= 0 and
x - r <= 9 * k):
# Find suffix of length
# k having sum of digits
# x-r
suf = helper(k,
x - r);
pre = "";
if (i > 0):
pre = y[0 : i]
# Append current
# character
cur = chr(j +
ord('0'))
pre += cur;
# Return the result
return pre + suf;
i -= 1
k += 1
# Driver Code
if __name__ == "__main__":
# Given Number and Sum
x = 18;
y = 99;
# Function Call
print ( findMin(x, y))
# This code is contributed by Chitranayal
C#
// C# program for the above approach
using System;
using System.Text;
using System.Collections;
class GFG{
// Function to return the minimum string
// of length d having the sum of digits s
static string helper(int d, int s)
{
// Return a string of length d
StringBuilder ans = new StringBuilder();
for(int i = 0; i < d; i++)
{
ans.Append("0");
}
for(int i = d - 1; i >= 0; i--)
{
// Greedily put 9's in the end
if (s >= 9)
{
ans[i] = '9';
s -= 9;
}
// Put remaining sum
else
{
char c = (char)(s + (int)'0');
ans[i] = c;
s = 0;
}
}
return ans.ToString();
}
// Function to find the smallest
// number greater than Y
// whose sum of digits is X
static string findMin(int x, int Y)
{
// Convert number y to string
string y = Y.ToString();
int n = y.Length;
ArrayList p = new ArrayList();
for(int i = 0; i < n; i++)
{
p.Add(0);
}
// Maintain prefix sum of digits
for(int i = 0; i < n; i++)
{
p[i] = (int)((int) y[i] - (int)'0');
if (i > 0)
{
p[i] = (int)p[i] +
(int)p[i - 1];
}
}
// Iterate over Y from the back where
// k is current length of suffix
for(int i = n - 1, k = 0;; i--, k++)
{
// Stores current digit
int d = 0;
if (i >= 0)
{
d = (int) y[i] - (int)'0';
}
// Increase current digit
for(int j = d + 1; j <= 9; j++)
{
int r = j;
// Sum upto current prefix
if (i > 0)
{
r += (int) p[i - 1];
}
// Return answer if remaining
// sum can be obtained in suffix
if (x - r >= 0 && x - r <= 9 * k)
{
// Find suffix of length k
// having sum of digits x-r
string suf = helper(k, x - r);
string pre = "";
if (i > 0)
pre = y.Substring(0, i);
// Append current character
char cur = (char)(j + (int)'0');
pre += cur;
// Return the result
return pre + suf;
}
}
}
}
// Driver code
public static void Main(string[] arg)
{
// Given number and sum
int x = 18;
int y = 99;
// Function call
Console.Write(findMin(x, y));
}
}
// This code is contributed by rutvik_56
JavaScript
<script>
// Javascript program for the above approach
// Function to return the minimum String
// of length d having the sum of digits s
function helper(d, s)
{
// Return a String of length d
let ans = [];
for(let i = 0; i < d; i++)
{
ans.push("0");
}
for(let i = d - 1; i >= 0; i--)
{
// Greedily put 9's in the end
if (s >= 9)
{
ans[i] ='9';
s -= 9;
}
// Put remaining sum
else
{
let c = String.fromCharCode(
s + '0'.charCodeAt(0));
ans[i] = c;
s = 0;
}
}
return ans.join("");
}
// Function to find the smallest
// number greater than Y
// whose sum of digits is X
function findMin(x, Y)
{
// Convert number y to String
let y = Y.toString();
let n = y.length;
let p = [];
for(let i = 0; i < n; i++)
{
p.push(0);
}
// Maintain prefix sum of digits
for(let i = 0; i < n; i++)
{
p[i] = y[i].charCodeAt(0) -
'0'.charCodeAt(0);
if (i > 0)
{
p[i] = p[i] + p[i - 1];
}
}
// Iterate over Y from the back where
// k is current length of suffix
for(let i = n - 1, k = 0;; i--, k++)
{
// Stores current digit
let d = 0;
if (i >= 0)
{
d = y[i].charCodeAt(0) -
'0'.charCodeAt(0);
}
// Increase current digit
for(let j = d + 1; j <= 9; j++)
{
let r = j;
// Sum upto current prefix
if (i > 0)
{
r += p[i - 1];
}
// Return answer if remaining
// sum can be obtained in suffix
if (x - r >= 0 && x - r <= 9 * k)
{
// Find suffix of length k
// having sum of digits x-r
let suf = helper(k, x - r);
let pre = "";
if (i > 0)
pre = y.substring(0, i);
// Append current character
let cur = String.fromCharCode(
j + '0'.charCodeAt(0));
pre += cur;
// Return the result
return pre + suf;
}
}
}
}
// Driver code
// Given number and sum
let x = 18;
let y = 99;
// Function call
document.write(findMin(x, y));
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(log10Y)
Auxiliary Space: O(log10Y)
Similar Reads
Smallest number greater than or equal to X whose sum of digits is divisible by Y Given two integers X and Y, the task is to find the smallest number greater than or equal to X whose sum of digits is divisible by Y. Note: 1 <= X <= 1000, 1 <= Y <= 50.Examples: Input: X = 10, Y = 5 Output: 14 Explanation: 14 is the smallest number greater than 10 whose sum of digits (1
7 min read
Count numbers (smaller than or equal to N) with given digit sum Given a number N and a sum S, find the count of numbers upto N that have digit sum equal to S. Examples: Input : N = 100, S = 4 Output : 5 Upto 100 only 5 numbers(4, 13, 22, 31, 40) can produce 4 as their sum of digits. Input : N = 1000, S = 1 Output : 4 Upto 1000 only 4 numbers(1, 10, 100 and 1000)
8 min read
Smallest number whose product with N has sum of digits equal to that of N Given an integer N, the task is to find the smallest positive integer, which when multiplied by N, has sum of digits equal to the sum of digits of N. Examples: Input: N = 4Output: 28Explanation: Sum of digits of N = 44 * 28 = 112Sum of digits = 1 + 1 + 2 = 4, which is equal to sum of digits of N. In
6 min read
Smallest number greater than or equal to N having sum of digits not exceeding S Given integer N and integer S, the task is to find the smallest number greater than or equal to N such that the sum of its digits does not exceed S. Examples: Input: N = 3, S = 2Output: 10Explanation: Sum of digits of 10 is 1, which is less than 2. Input: N = 19, S = 3Output: 20Explanation: Sum of d
6 min read
Find the kth smallest number with sum of digits as m Given two integers M and K, the task is to find the Kth smallest number with digit sum as M.Examples: Input: M = 5, K = 3 Output: 23 Sequence of numbers starting from 1 with digit sum as 5 is as follows: 5 14 23 32 41 So 3rd smallest number is 23Input: M = 4, K = 1 Output: 4 Approach: We need to fin
6 min read
Smallest number greater than or equal to N which is divisible by its non-zero digits Given an integer N, the task is to find the smallest number greater than or equal to N such that it is divisible by all of its non-zero digits. Examples: Input: N = 31Output: 33Explanation: 33 is the smallest number satisfying the given condition. At Unit's place: 33%3 = 0At One's place: 33%3 = 0 In
7 min read
Smallest number k such that the product of digits of k is equal to n Given a non-negative number n. The problem is to find the smallest number k such that the product of digits of k is equal to n. If no such number k can be formed then print "-1".Examples: Input : 100 Output : 455 Explanation: 4*5*5 = 100 and 455 is the smallest possible number. Input : 26 Output : -
10 min read
Minimum numbers (smaller than or equal to N) with sum S Given N numbers(1, 2, 3, ....N) and a number S. The task is to print the minimum number of numbers that sum up to give S. Examples: Input: N = 5, S = 11 Output: 3 Three numbers (smaller than or equal to N) can be any of the given combinations. (3, 4, 4) (2, 4, 5) (1, 5, 5) (3, 3, 5)Input: N = 1, S =
3 min read
Find the smallest number whose sum of digits is N Given a positive integers N, the task is to find the smallest number whose sum of digits is N.Example: Input: N = 10Output: 19Explanation: 1 + 9 = 10 = N Input: N = 18Output: 99Explanation: 9 + 9 = 18 = N Naive Approach: A Naive approach is to run a loop of i starting from 0 and find Sum of digits o
6 min read
Least Greater number with same digit sum Given a number represented in the form of an array such that each element of the array stores a single digit of the number. That is, array for the number 1234 will be arr[] = {1,2,3,4}. The task is to find the least number greater than the given number but having the sum of digits equal to the given
10 min read