Find a N-digit number such that it is not divisible by any of its digits
Given an integer N, the task is to find an N-digit number such that it is not divisible by any of its digits.
Note: There can be multiple answers for each value of N.
Input: N = 4
As the number 6789 is not divisible by any of its digits, it is 6, 7, 8 and 9 and it is also a four-digit number. Hence, it can be the desired number.
Input: N = 2
As the number 57 is not divisible by any of its digits, it is 5 and 7 and it is also a 2-digit number. Hence, it can be the desired number.
Approach: The key observation in the problem is that 2 and 3 are those numbers that don’t divide each other. Also, the numbers “23, 233, 2333, …” are not divisible by neither 2 nor 3. Hence, for any N-digit number, the most significant digit will be 2 and the rest of the digits will be 3 to get the desired number.
- Check if the value of the N is equal to 1, then there is no such number is possible, hence return -1.
- Otherwise, initialize a variable num, to store the number by 2.
- Run a loop from 1 to N and then, for each iteration, multiply the number by 10 and add 3 to it.
num = (num * 10) + 3
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.