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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <cmath>
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.