Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- != 0) {
int n = sc.nextInt();
int[] a = new int[n + 1];
a[1] = 1;
int i = 2;
int c = 0;
while (a[n] == 0) {
if ((a[i - 1] + c) % 2 == 0 || (a[i - 1] + c) % 3 == 0 || (a[i - 1] + c) % 5 == 0) {
a[i] = a[i - 1] + c;
i++;
c = 0;
}
c++;
}
System.out.println(a[n]);
}
Ugly numbers test case not passing
Try for this
1
176
correct output : 10125
your code gives : 238 // not ugly
logic :
Ugly number(i) = minimum of (2 * ugly number(f2), 3* ugly number(f3), 5*ugly number(f5))
Where, f2, f3, f5 are counters for 2, 3, 5 respectively which stores the index for f2th ugly number, f3th ugly number, f5th ugly number.
Then we will store our answer.
Algorithm:
Initializing f2, f3, f5 to maintain f2th ugly number, f3th ugly number and f5th ugly number to 1.
Creating a DP matrix in which ith cell represent ith ugly number.
Start filling the dp matrix from i = 2.
Ugly number(i) = minimum of (2 * ugly number(f2), 3* ugly number(f3), 5*ugly number(f5)).
Finding the answer using above relation and storing it at ith index.
Now, the time complexity O(N).