求100以内的素数(质数),求素数算法

#include<math.h>
#include<iomanip>
#include <iostream>
using namespace std;
#define N 101
int main(){
    int i,j,line,a[N];
    
    for(i=1;i<N;i++)  a[i]=i;    /*初始化数组*/
   
   for(i=2;i<N;i++)//遍历所有数
 {
  for(j=2;j<=sqrt(i);j++)//遍历除数,看是否有除数能整除
  {
   if(a[i]%j==0)//不是素数
   {
    a[i]=0;
    break;
   }
  }
 }
    cout<<endl;
   
    for(i=2,line=0;i<N;i++){
       if(a[i]!=0){
           cout<<setw(5)<<a[i];
           line++;
           }
       if(line==10){
           cout<<endl;
           line=0;
           }
    }
    cout<<endl;
 return 0;

posted @ 2008-11-10 11:27  凌点  阅读(2903)  评论(0编辑  收藏  举报