// Hamming's problem
// Algorithm invented by Dijsktra
// Send bugs to tony.bruguier@gmail.com

#include <stdio.h>
void ham(const unsigned long *p, const size_t np, unsigned long *q, const size_t n)
{
    size_t *idx = new size_t[np];
    // Init
    q[0] = 1;
    for(size_t ii = 0; ii < np; ++ii)
        idx[ii] = 0;
    
    // Loop
    for(size_t jj = 1; jj < n; ++jj)
        {
        // Find the min and put in the array
        q[jj] = (unsigned long)-1;
        for(size_t ii = 0; ii < np; ++ii)
            {
            unsigned long val = p[ii] * q[idx[ii]];
            if(val < q[jj])
            q[jj] = val;
            }
        
        // Then increase the indices
        for(size_t ii = 0; ii < np; ++ii)
            {
            while(p[ii] * q[idx[ii]] <= q[jj])
            idx[ii]++;
            }
        }
    
    delete [] idx;
}

int main(int argc, char **argv)
{
    // Input variables
    unsigned long primes[] = {2, 5};
    size_t n = 10;
    
    // Call the function
    size_t np = sizeof(primes) / sizeof(unsigned long);
    unsigned long *q = new unsigned long[n];
    ham(primes, np, q, n);
    
    // Print result
    for(size_t ii = 0; ii < n; ++ii)
        printf("%lu\n", q[ii]);
        
    // Clean up and exit
    delete [] q;
    return 0;
}

