Smallest number not less than N which is divisible by all digits of N
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++
#include "bits/stdc++.h"
using namespace std;
int LCM( int A, int B)
{
return (A * B / __gcd(A, B));
}
int findSmallestNumber( int X)
{
int lcm = 1;
int temp = X;
while (temp) {
int last = temp % 10;
temp /= 10;
if (!last)
continue ;
lcm = LCM(lcm, last);
}
int answer = ((X + lcm - 1) / lcm)
* lcm;
cout << answer;
}
int main()
{
int X = 280;
findSmallestNumber(X);
return 0;
}
|
Java
class GFG{
static int LCM( int A, int B)
{
return (A * B / __gcd(A, B));
}
static void findSmallestNumber( int X)
{
int lcm = 1 ;
int temp = X;
while (temp > 0 )
{
int last = temp % 10 ;
temp /= 10 ;
if (last == 0 )
continue ;
lcm = LCM(lcm, last);
}
int answer = ((X + lcm - 1 ) / lcm)
* lcm;
System.out.print(answer);
}
static int __gcd( int a, int b)
{
return b == 0 ? a:__gcd(b, a % b);
}
public static void main(String[] args)
{
int X = 280 ;
findSmallestNumber(X);
}
}
|
Python3
import math
def LCM(A, B):
return (A * B / / math.gcd(A, B))
def findSmallestNumber(X):
lcm = 1
temp = X
while (temp):
last = temp % 10
temp / / = 10
if ( not last):
continue
lcm = LCM(lcm, last)
answer = ((X + lcm - 1 ) / / lcm) * lcm
print (answer)
if __name__ = = "__main__" :
X = 280
findSmallestNumber(X)
|
C#
using System;
class GFG{
static int LCM( int A, int B)
{
return (A * B / __gcd(A, B));
}
static void findSmallestNumber( int X)
{
int lcm = 1;
int temp = X;
while (temp > 0)
{
int last = temp % 10;
temp /= 10;
if (last == 0)
continue ;
lcm = LCM(lcm, last);
}
int answer = ((X + lcm - 1) / lcm)
* lcm;
Console.Write(answer);
}
static int __gcd( int a, int b)
{
return b == 0 ? a:__gcd(b, a % b);
}
public static void Main(String[] args)
{
int X = 280;
findSmallestNumber(X);
}
}
|
Javascript
<script>
function LCM(A,B)
{
return (A * B / __gcd(A, B));
}
function findSmallestNumber(X)
{
let lcm = 1;
let temp = X;
while (temp > 0)
{
let last = temp % 10;
temp = Math.floor(temp/10);
if (last == 0)
continue ;
lcm = LCM(lcm, last);
}
let answer = Math.floor((X + lcm - 1) / lcm)
* lcm;
document.write(answer);
}
function __gcd(a,b)
{
return b == 0 ? a:__gcd(b, a % b);
}
let X = 280;
findSmallestNumber(X);
</script>
|
Time Complexity: O(N*log10N)
Auxiliary Space: O(1)
Last Updated :
02 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...