|
发表于 2004-2-11 10:39:29
|
显示全部楼层
它的is_prime,就是判断n是不是质数
从2开始试,直到跟号下n,如果都不能被整出,就是质数
当然这个方法很慢拉,我给你一个快点的吧
[code:1]
#include <vector>
#include <iostream>
using namespace std;
typedef vector<long> num_list_t;
num_list_t prime_nums;
void find_prime_numbers(num_list_t &prime_nums, long max);
int main(int argc, char *argv[])
{
num_list_t num_list;
int max = 0;
while (max != -1) {
cin >> max;
find_prime_numbers(num_list, max);
copy(num_list.begin(), num_list.end(), ostream_iterator<long>(cout, "\n"));
cout << endl;
num_list.clear();
}
system("pause");
return 0;
}
void find_prime_numbers(num_list_t &prime_nums, long max)
{
if (max < 2) return;
else if (max == 2) prime_nums.push_back(2);
else {
bool *table = new bool[max+1];
memset(table, 1, max+1);
find_prime_numbers(prime_nums, max / 2);
for (long i = 0; i < prime_nums.size(); i++) {
for (long j = prime_nums[i]; j <= max; j += prime_nums[i])
table[j] = false;
}
for (long k = max/2 + 1; k <= max; k++)
if (table[k])
prime_nums.push_back(k);
delete []table;
}
}
[/code:1] |
|