1.首先我们要先判断什么是质数(质数是除了1和自身能整除,其他数字都不能整除的数)
其次还要判断口袋里的数字之和不能大于负载量。
2.运用了for循环和while循环来判断出从2到a中的所有质数,又利用if语句判断出符合条件的数
题解中还运用了vector容器(一种变长数组,stl中的部件)
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,s,sum=0;
vector<int> b;
cin >> a;
if(a>2){
b.push_back(2);
for(int i=3; i<=a; i++){
s = 2;
while(s != i){
if(i%s != 0){
s++;
}
else if(i%s == 0){
break;
}
}
if(s == i){
sum += i;
if(sum <= a){
b.push_back(i);
}
}
}
vector<int>::iterator it = b.begin();
for(it=b.begin(); it!=b.end(); it++){
cout << *it << endl;
}
cout << b.size() << endl;
}
if(a == 2){
cout << 2 << endl;
cout << 0 << endl;
}
if(a<2){
cout << 0 << endl;
}
return 0;
}
2.运行结果