C++学习之路 | PTA乙级—— 1013 数素数 (20分)(精简)
生活随笔
收集整理的這篇文章主要介紹了
C++学习之路 | PTA乙级—— 1013 数素数 (20分)(精简)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1013 數素數 (20分)
令 P
?i
?? 表示第 i 個素數。現任給兩個正整數 M≤N≤10
?4
?? ,請輸出 P
?M
?? 到 P
?N
?? 的所有素數。
輸入格式:
輸入在一行中給出 M 和 N,其間以空格分隔。
輸出格式:
輸出從 P
?M
?? 到 P
?N
?? 的所有素數,每 10 個數字占 1 行,其間以空格分隔,但行末不得有多余空格。
輸入樣例:
5 27
輸出樣例:
11 13 17 19 23 29 31 37 41 43
47 53 59 61 67 71 73 79 83 89
97 101 103
這題當時就是運行超時,想了很久,才發現這里檢測很嚴,在給定1—10000范圍內,第一萬個素數恰好是104729,所以給定的范圍i不能太大。
#include<iostream> #include<math.h> using namespace std; bool judge(int n)//求素數模板 {if (n < 2) return false;for (int i = 2; i <= sqrt(n); i++){if (n % i == 0) return false;}return true; } int main() {int m, n, count = 0, j = 0;//count記錄素數個數,j用來控制換行,10個換一行cin >> m >> n;for (int i = 0; i <= 104729; i++){if (judge(i))//判斷素數{count++;//記錄加1if (count >= m && count <= n)//在給定空間內{if (j == 0)cout << i;//第一個數不為空格else if (j % 10 == 0 && j != 0)cout << endl << i;//換行else cout << " " << i;j++;}//取消下面注釋可以查看第一萬個素數大小。//if (count == 10000)//{// cout << i;//}}} }下面是柳神的代碼
#include <iostream> #include <vector> using namespace std; bool isprime(int a) {for (int i = 2; i * i <= a; i++)if(a % i == 0) return false;return true; } int main() {int M, N, num = 2, cnt = 0;cin >> M >> N;vector<int> v;while (cnt < N) {if (isprime(num)) {cnt++;if (cnt >= M) v.push_back(num);}num++;}cnt = 0;for (int i = 0; i < v.size(); i++) {cnt++;if (cnt % 10 != 1) printf(" ");printf("%d", v[i]);if (cnt % 10 == 0) printf("\n");}return 0; }總結
以上是生活随笔為你收集整理的C++学习之路 | PTA乙级—— 1013 数素数 (20分)(精简)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java xml 序列化_java-序列
- 下一篇: C++学习之路 | PTA(天梯赛)——