主题:如何用筛法求素数?
XVenus
[专家分:20] 发布于 2005-06-19 15:07:00
请问如何用筛法求素数?
回复列表 (共25个回复)
21 楼
cedricporter [专家分:0] 发布于 2007-04-15 11:24:00
#include <iostream>
#include <cmath>
using namespace std;
const long max_size = 1000000;
int main()
{
bool a[max_size];
for (long i = 0; i < max_size; i++)
a[i] = true;
long n;
cin >> n;
for (long j = 2; j <= long(sqrt(n)); j++)
for (long k = 2; k <= n; k++)
if (k % j == 0 && k != j)
a[k] = false;
for (int v = 2; v <= n; v++)
if (a[v])
cout << v << ' ';
system("pause");
return 0;
}
22 楼
waglongjuanfeng [专家分:90] 发布于 2007-06-14 17:45:00
<求1..50000内的素数,顺便建立素数表>
已编译>>>
var a,b,c,d:longint;
l:integer;
i,j,k:longint;
prime:array[1..5200] of longint;
procedure getprime;
var i,j:longint;
p:array[1..50000] of boolean;
begin
fillchar(p,sizeof(p),true);
p[1]:=false;
i:=2;
while i<50000 do begin
if p[i] then
begin
j:=2*i;
while j<50000 do
begin
p[j]:=false;
inc(j,i);
end;
end;
inc(i);
end;
l:=0;
for i:=1 to 50000 do
if p[i] then
begin
inc(l);
prime[l]:=i;
end;
end;
begin
getprime;
writeln(l);
readln;
end.
23 楼
vvian00 [专家分:0] 发布于 2008-08-12 18:07:00
[quote][quote你能找到它的源程序吗?
发给我:zhxd300@163.com[/quote]
已发。[/quote]
能不能也给我一份
谢谢!
vvian00 AT qq DOT com
24 楼
cylixstar [专家分:60] 发布于 2008-08-22 20:25:00
#include<iostream>
#include<vector>
using namespace std;
const long n=100000000;
int main()
{
vector<bool> P(N + 1, true);
vector<long> Primes;
long Time = 0;
for (long I = 2; I <= N; I++)
{
if (P[I])
{
Primes.push_back(I);
Time++;
}
for (long J = 0; J < (int)Primes.size() && I * Primes[J] <= N; J++)
{
P[I * Primes[J]] = false;
Time++;
if (I % Primes[J] == 0) break;
}
}
cout << Time << " " << Primes.size() << endl;
}
线性时间筛法求素数,1亿也是一两秒的时间
25 楼
XVenus [专家分:20] 发布于 2008-11-16 16:17:00
十秒钟都没出答案啊~~
[quote]#include<iostream>
#include<vector>
using namespace std;
const long n=100000000;
int main()
{
vector<bool> P(N + 1, true);
vector<long> Primes;
long Time = 0;
for (long I = 2; I <= N; I++)
{
if (P[I])
{
Primes.push_back(I);
Time++;
}
for (long J = 0; J < (int)Primes.size() && I * Primes[J] <= N; J++)
{
P[I * Primes[J]] = false;
Time++;
if (I % Primes[J] == 0) break;
}
}
cout << Time << " " << Primes.size() << endl;
}
线性时间筛法求素数,1亿也是一两秒的时间[/quote]
我来回复