Ugly numbers are those numbers whose only prime factors are 2, 3, and 5. The first seven ugly numbers are 1, 2, 3, 4, 5, 6, 8, where 1 is an exception. You are given an integer ‘N’, print the ‘Nth’ ugly number. As the ugly number can be large, print the result modulo 10^9 + 7.
For example:Let ‘N’ be: 10
The 10th ugly number is: 12
The first line of the input contains a single integer 'T', representing the number of test cases.
The first line of each test case contains a single integer ‘N’.
Output Format :
For each test case, print a single integer representing the ‘Nth’ ugly number.
Print the output of each test case in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^4
Time Limit: 1 sec
2
10
1
12
1
For the first test case :
The 10th ugly number is 12.
For the second test :
The 1st ugly number is 1.
2
15
150
24
5832
Try to find the count of ugly numbers less than a number.
The basic idea is to find the count of ugly numbers present less than a given number ‘N’. We use binary search to find the count. We initialize a range in which the result will be present and then use binary search to find the count of ugly numbers smaller than a number. We find it by finding the count of ugly numbers which are multiples of 2, 3, and 5, multiples of both 2 and 3, 3 and 5, and 2 and 5, and multiple of 2, 3, and 5.
Here is the algorithm :
HELPER(‘MID’)
HELP1(‘MID’, ‘VAL’) (where ‘VAl’ is multiple)
HELP2(‘MID’, ‘VAL1’, ‘VAL2’) (where ‘VAl1’ and ‘VAL2’ are multiples)
HELP3(‘MID’, ‘VAL1’, ‘VAL2’, ‘VAL3’) (where ‘VAL1’, ‘VAL2’, and ‘VAL3’ are multiples)
O((log(10^18))^4)
We use binary search to find the number having a count of ugly numbers smaller than ‘N’, which takes O(log(10^18)) time, and finding count of the ugly numbers smaller than a number that takes O(log(10^18)^3) time. Therefore, the overall time complexity will be O(log(10^18)^4), i.e., O(1).
O(log(10^18))
The recursive stack to count the ugly numbers smaller than ‘N’ can have O(log(10^18)) space. Therefore, the overall space complexity will be O(1).