The Wayback Machine - https://web.archive.org/web/20210107132731/https://www.geeksforgeeks.org/smallest-number-not-less-than-n-which-is-divisible-by-all-digits-of-n/
Related Articles

Related Articles

Smallest number not less than N which is divisible by all digits of N
  • Last Updated : 07 Jan, 2021

Given a positive integer N, the task is to find the smallest integer greater than or equal to X, having all its digits divisible by the non-zero digits of N.

Examples:

Input: N = 280
Output: 280
Explanation:
280 is the smallest which is divisible by the digits 8 and 2.

Input: N = 32
Output: 36
Explanation:
36 is the smallest number which is divisible by both the digits 2 and 3.

Approach: The idea is to find the LCM of all the non-zero digits of X and then just find the next greater multiple of that LCM value which is greater than N.



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;
  
// Function to calculate the LCM
int LCM(int A, int B)
{
    return (A * B / __gcd(A, B));
}
  
// Function to find the smallest number
// satisfying given constraints
int findSmallestNumber(int X)
{
    // LCM value is 1 initially
    int lcm = 1;
    int temp = X;
  
    // Finding the LCM of all
    // non zero digits
    while (temp) {
  
        int last = temp % 10;
        temp /= 10;
  
        if (!last)
            continue;
  
        // Update the value lcm
        lcm = LCM(lcm, last);
    }
  
    // Stores ceil value
    int answer = ((X + lcm - 1) / lcm)
                 * lcm;
  
    // Print the answer
    cout << answer;
}
  
// Dtiver Code
int main()
{
    int X = 280;
  
    // Function Call
    findSmallestNumber(X);
  
    return 0;
}

chevron_right


Output:

280

Time Complexity: O(N*log10N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :