A friend of mine is interviewing for a job. One of the interview questions got me thinking, just wanted some feedback.
There are 2 non-negative integers: i and j. Gi
The algorithm implemented by user515430 by Edsger Dijkstra (http://www.cs.utexas.edu/users/EWD/ewd07xx/EWD792.PDF) is probably as fast as you can get. I call every number that is a form of 2^i * 5^j a "special number". Now vlads answer would be O(i*j) but with a double algorithm, one to generate the special numbers O(i*j) and one to sort them (according to the linked article also O(i*j).
But let's check Dijkstra's algorithm (see below). In this case n is the amount of special numbers we are generating, so equal to i*j. We are looping once, 1 -> n and in every loop we perform a constant action. So this algorithm is also O(i*j). And with a pretty blazing fast constant too.
My implementation in C++ with GMP (C++ wrapper), and dependancy on boost::lexical_cast, though that can be easily remove (I'm lazy, and who doesn't use Boost?). Compiled with g++ -O3 test.cpp -lgmpxx -o test. On Q6600 Ubuntu 10.10 time ./test 1000000 gives 1145ms.
#include
#include
#include
int main(int argc, char *argv[]) {
mpz_class m, x2, x5, *array, r;
long n, i, i2, i5;
if (argc < 2) return 1;
n = boost::lexical_cast(argv[1]);
array = new mpz_class[n];
array[0] = 1;
x2 = 2;
x5 = 5;
i2 = i5 = 0;
for (i = 1; i != n; ++i) {
m = std::min(x2, x5);
array[i] = m;
if (x2 == m) {
++i2;
x2 = 2 * array[i2];
}
if (x5 == m) {
++i5;
x5 = 5 * array[i5];
}
}
delete [] array;
std::cout << m << std::endl;
return 0;
}