#include<iostream>usingnamespace std;#define maxn 1000000bool valid[maxn];voidgetPrime(int n,int& tot,int ans[maxn]){
tot =0;int i, j;for(i =2; i <= n; i++) valid[i]=true;for(i =2; i <= n; i++)if(valid[i]){
ans[++tot]= i;for(j = i * i; j <= n; j += i) valid[j]=false;}}intmain(){int n =100;int tot =0;int ans[maxn];getPrime(n, tot, ans);for(int i =1; i <= tot; i++){
cout << ans[i]<<" ";}
cout << endl <<"total: "<< tot << endl;return0;}
JAVA
publicclassPrime{privatestaticboolean[] valid;publicstaticintgetPrime(int n,int[] ans){int tot =0;
valid =newboolean[n +1];int i, j;for(i =2; i <= n; i++) valid[i]=true;for(i =2; i <= n; i++)if(valid[i]){
ans[++tot]= i;for(j = i * i; j <= n; j += i) valid[j]=false;}return tot;}publicstaticvoidmain(String[] args){int n =100;int[] ans =newint[n +1];int tot =getPrime(n, ans);for(int i =1; i <= tot; i++){
System.out.print(ans[i]);if(i < tot) System.out.print(", ");else System.out.println();}
System.out.println("total: "+ tot);}}
Python
defgetPrime(n, tot_, ans):
tot =0
valid =[Truefor i inrange(n +1)]for i inrange(2, n):if valid[i]:
tot +=1
ans[tot]= i
for j inrange(i * i, n +1, i):
valid[j]=False
tot_[0]= tot
if __name__ =='__main__':
n =100
tot =[0]
ans =[0for i inrange(n +1)]
getPrime(n, tot, ans)for i inrange(1, tot[0]+1):print(ans[i], end=',')print()print(tot[0])
O(N)篩法
C++
#include<iostream>usingnamespace std;#define maxn 1000000bool valid[maxn];voidgetPrime(int n,int& tot,int ans[maxn]){
tot =0;memset(valid,true,sizeof(valid));for(int i =2; i <= n; i++){if(valid[i]){++tot;
ans[tot]= i;}for(int j =1;((j <= tot)&&(i * ans[j]<= n)); j++){
valid[i * ans[j]]=false;if(i % ans[j]==0)break;}}}intmain(){int n =100;int tot =0;int ans[maxn];getPrime(n, tot, ans);for(int i =1; i <= tot; i++){
cout << ans[i]<<" ";}
cout << endl <<"total: "<< tot << endl;return0;}
JAVA
import java.util.Arrays;publicclassPrime{privatestaticboolean[] valid;publicstaticintgetPrime(int n,int[] ans){int tot =0;
valid =newboolean[n +1];
Arrays.fill(valid,true);for(int i =2; i <= n; i++){if(valid[i]){
ans[++tot]= i;}for(int j =1;((j <= tot)&&(i * ans[j])<= n); j++){
valid[i * ans[j]]=false;if(i % ans[j]==0)break;}}return tot;}publicstaticvoidmain(String[] args){int n =100;int[] ans =newint[n +1];int tot =getPrime(n, ans);for(int i =1; i <= tot; i++){
System.out.print(ans[i]);if(i < tot) System.out.print(", ");else System.out.println();}
System.out.println("total: "+ tot);}}
Python
defgetPrime(n, tot_, ans):
tot =0
valid =[Truefor i inrange(n +1)]for i inrange(2, n):if valid[i]:
tot +=1
ans[tot]= i
for j inrange(1, tot +1):if i * ans[j]> n:break
valid[i * ans[j]]=Falseif i % ans[j]==0:break
tot_[0]= tot
if __name__ =='__main__':
n =100
tot =[0]
ans =[0for i inrange(n +1)]
getPrime(n, tot, ans)for i inrange(1, tot[0]+1):print(ans[i], end=',')print()print(tot[0])