1. 程式人生 > >基礎編程復習:輸出n以內的所有素數

基礎編程復習:輸出n以內的所有素數

滿足 scanf col ostream 素數 clas %d eof 只需要

暴力遍歷:對於1~n以內的每一數i

每一個i只需要考慮2~i開根號以內是否有可以讓i整除的數,即(i%x==0)只要滿足就不是素數

否則輸出

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cmath>
 4 using namespace std;
 5 int main()
 6 {
 7     int n,i;
 8     while(scanf("%d",&n)!=EOF)
 9     {
10         for(i=2; i<=n; i++)
11 { 12 int sqr=sqrt(i); 13 bool flag=true; 14 for(int j=2; j<=sqr; j++) 15 { 16 if(i%j==0) {flag=false; 17 break;} 18 } 19 if(flag) 20 cout<<i<< ;
21 } 22 cout<<endl; 23 } 24 return 0; 25 26 }

基礎編程復習:輸出n以內的所有素數