首先,贴上实现的源代码:
//
// main.cpp
// testC++1
//
// Created by fei dou on 12-7-26.
// Copyright (c) 2012年 vrlab. All rights reserved.
//
#include <iostream>
#include <cmath>
using namespace std;
void primeLessThanN( int n)
{
if(n < 1) return ;
bool *isPrime = new bool[n+1];//动态生成一个数组
memset((void*)isPrime, true, (n + 1)*sizeof(bool));
int sqrtOfN = sqrt(n);
isPrime[0] = false;
isPrime[1] = false;
for( int i = 0; i <= sqrtOfN; ++ i )
if(isPrime[i] == true)
for(int j = i*i; j <= n; j +=i)
isPrime[j] = false;
int count = 0;
for(int m = 0; m <= n ; m ++)
{
if(isPrime[m] == true)
{
printf("%-5d ",m);
++ count;
if( count % 5 == 0 )
printf("\n");
}
}
delete[] isPrime;//释放空间
}
int main (int argc, const char * argv[])
{
primeLessThanN(32768);
return 0;
}
本程序使用的是Sieve of Eratosthenes方法,这是一种快事求取小于N的所有素数的方法。
它的具体原理可以参考:http://en.wikipedia.org/wiki/Eratosthenes_Sieve
如果有什么不太名白的地方可以给我留言,大家一起探讨!