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


暴力遍歷:對於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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM