@Pen72, Your code only checks if the number happens to have at least one factor of 2, 3, or 5, but in order to solve the problem it needs to check that the number ONLY contains those factors. So the naive implementation would be more like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int main()
{
int q;
cin >> q;
while (q--)
{
uint64_t n;
cin >> n;
auto m = n;
while (m % 2 == 0) m /= 2;
while (m % 3 == 0) m /= 3;
while (m % 5 == 0) m /= 5;
if (m == 1) cout << n << '\n';
}
}
The naive implementation may be good enough for this problem since for 64-bit unsigned values there can only be a maximum of 63 factors of 2, 40 factors of 3, or 27 factors of 5.
1
18446744073709551615 (max unsigned 64-bit value - 1)
This example will overflow - but you've got to stop somewhere. Nothing is stated in the question about range. Actually, neither your nor my code will solve the original question for this input - see below.
Why do you imply that my code is wrong for the second example? I thought the queries were supposed to ask for the kth ugly number - NOT whether the input is or is not an ugly number. Neither your code nor the OP's flawed code reflect the question.
Original question:
The first line has a integer q. It is meaning there are q queries. Each query only contains a integer k.
For each query, print the value of the k-th ugly number.
For input
10
11 12 13 14 15 16 17 18 19 20
my code gives output
15
16
18
20
24
25
27
30
32
36
Since the ugly numbers (according to the definition given in the original post) are
you should be able to directly compute it.
the pattern is
a*2, a*3, a*5, (a+1)*2, (a+1)*3, ...
so the kth number is some mashup of k/3 and k%3.. right?
edit, its not a++ though, is it... that is what you were saying above.
its a = 2,3,5 cycled off previous values. Hmm.