Given three integers X, Y and N, the task is to find the largest number possible of length N consisting only of X and Y as its digits, such that, the count of X‘s in it is divisible by Y and vice-versa. If no such number can be formed, print -1.
Input: N = 3, X = 5, Y = 3
Count of 5’s = 3, which is divisible by 3
Count of 3’s = 0
Input: N = 4, X = 7, Y = 5
Follow the steps below to solve the problem:
- Consider the larger of X and Y as X and smaller as Y.
- Since, the number needs to of length N, perform the following two steps until N ≤ 0:
- If N is divisible by Y, append X, N times to the answer and reduce N to zero.
- Otherwise, reduce N by X and append Y, X times to the answer.
- After completion of the above step, if N <0, then a number of required type is not possible. Print -1.
- Otherwise, print the answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
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.
- Largest number divisible by 90 that can be made using 0 and 5
- Count N-digit numbers made up of X or Y whose sum of digits is also made up of X or Y
- Find two numbers made up of a given digit such that their difference is divisible by N
- Count the number of pairs (i, j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]
- Largest divisor of a number not divisible by another given number
- Number of digits in the nth number made of given four digits
- Largest number with the given set of N digits that is divisible by 2, 3 and 5
- Count of Rectangles with area K made up of only 1s from given Binary Arrays
- Largest K digit number divisible by X
- C++ Program for Largest K digit number divisible by X
- Java Program for Largest K digit number divisible by X
- Sum of largest divisible powers of p (a prime number) in a range
- Largest number smaller than or equal to N divisible by K
- Largest N digit number divisible by given three numbers
- Sum of largest divisor of numbers upto N not divisible by given prime number P
- Largest Divisor of a Number not divisible by a perfect square
- Finding n-th number made of prime digits (2, 3, 5 and 7) only
- Smallest multiple of a given number made of digits 0 and 9 only
- Number of words that can be made using exactly P consonants and Q vowels from the given string
- Check if X and Y can be made zero by using given operation any number of times
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.