### Hamming numbers algorithm

Hi everybody, I am doing a program that is supposed to print the n first hamming numbers, where n is a number given.

Code works OK, but too slow to be accepted for an online evaluator.

**There is some stuff on the main function just because of the commas between numbers that are asked to appear.

Here it is:
 ``1234567891011121314151617181920212223242526272829303132333435363738`` ``````#include #include using namespace std; bool is_hamming (int n) { if (n == 1) return true; if (n%2==0 or n%3==0 or n%5==0) { for (int i = 2; i*i < n; ++i) { if (n%i == 0) { if (i%2 != 0 and i%3!=0 and i%5!=0) return false; } if (n%(n/i) == 0) { if ((n/i)%2 != 0 and (n/i)%3!=0 and (n/i)%5!=0) return false; } } return true; } return false; } int main () { int n; while (cin >> n) { int count = 0; int i = 1; bool first = true; while (count < n) { if (is_hamming(i)) { if (not first) cout << ","; cout << i; ++count; first = false; } ++i; } } } ``````
Topic archived. No new replies allowed.