洛谷-P5723 【深基4.例13】質數口袋
阿新 • • 發佈:2020-07-18
洛谷-P5723 【深基4.例13】質數口袋
題目描述
小A 有一個質數口袋,裡面可以裝各個質數。他從 2 開始,依次判斷各個自然數是不是質數,如果是質數就會把這個數字裝入口袋。口袋的負載量就是口袋裡的所有數字之和。但是口袋的承重量有限,不能裝得下總和超過 \(L(1\le L\le100000)\) 的質數。給出 \(L\),請問口袋裡能裝下幾個質數?將這些質數從小往大輸出,然後輸出最多能裝下的質數個數,所有數字之間有一空行。
輸入格式
無
輸出格式
無
輸入輸出樣例
輸入 #1
100
輸出 #1
2
3
5
7
11
13
17
19
23
9
C++程式碼
#include <iostream> #include <cmath> using namespace std; bool isPrime(int n) { for (int i=2; i<=sqrt(n); ++i) if (n % i == 0) return false; return true; } int main() { int L, sum, count; cin >> L; sum = count = 0; for (int i=2; sum + i <= L; ++i) if (isPrime(i)) { sum += i; ++count; cout << i << '\n'; } cout << count << endl; return 0; }