ACMNO.17C語言-篩法求素數 用篩法求之N內的素數。
阿新 • • 發佈:2018-12-15
題目描述
用篩法求之N內的素數。
輸入
N
輸出
0~N的素數
樣例輸入
100
樣例輸出
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
提示
陣列大小動態定義?函式?
來源/分類
C語言
題目截圖:
思路:
這個以前就碰到的,要使用兩層for迴圈語句來解決! for(int i=1;i<s;i++) { //cout<<"i開始: "<<i<<endl; a=0; for(int j=1;j<i;j++) {} } 篩選素數,的條件,不能為自身和1!還不能有因子。 if(i%j==0&&i!=j&&j!=1) 最後輸出,不能輸出1! if(a!=1&&i!=1) {cout<<i<<endl;} //<<endl<<endl<<"最後: "
程式碼:
#include<iostream> using namespace std; int main() { int a,b,s; cin>>s; for(int i=1;i<s;i++) { //cout<<"i開始: "<<i<<endl; a=0; for(int j=1;j<i;j++) { if(i%j==0&&i!=j&&j!=1) { a=1; } //cout<<"j: "<<j<<endl; } if(a!=1&&i!=1) {cout<<i<<endl;}//<<endl<<endl<<"最後: " } }
程式碼截圖:
程式碼執行截圖:
OJ結果: