VOOZH about

URL: https://www.geeksforgeeks.org/dsa/largest-n-digit-number-divisible-by-given-three-numbers/

⇱ Largest N digit number divisible by given three numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest N digit number divisible by given three numbers

Last Updated : 21 Mar, 2023

Given four integers x, y, z, and n, the task is to find the largest n digit number which is divisible by x, y, and z

Examples:

Input: x = 2, y = 3, z = 5, n = 4 
Output: 9990 
9990 is the largest 4-digit number which is divisible by 2, 3 and 5.
Input: x = 3, y = 23, z = 6, n = 2 
Output: Not possible 

Approach:  

  • Find the largest n digit number i.e. pow(10, n) - 1 and store it in a variable largestN.
  • Find LCM of the given three numbers x, y and z say LCM.
  • Calculate the remainder when largestN is divided by LCM i.e. largestN % LCM and store it in a variable remainder.
  • Subtract remainder from largestN. If the result is still an n digit number then print the result.
  • Else print Not possible.


Below is the implementation of the above approach:
 


Output: 
96

 

Time Complexity: O(log(min(x, y,z ))) + O(log(n)) as we are doing lcm of x,y,z we need log(min(x,y,z)) time complexity for that + log(n) for doing pow(10,n-1) so overall time complexity will be O(log(min(x, y,z ))) + O(log(n))

Auxiliary Space: O(log(min(x, y, z))) + O(log(n)) as we are doing lcm of x,y,z this lcm will be done in recursively manner so recursion need extra O(log(min(x, y, z))) auxiliary stack space, and addition for doing pow(10,n-1) which is also in recursive manner which also need log(n) extra auxiliary stack space

Comment