题目描述
小 A 有一个质数口袋,里面可以装各个质数。他从 2 开始,依次判断各个自然数是不是质数,如果是质数就会把这个数字装入口袋。
口袋的负载量就是口袋里的所有数字之和。
但是口袋的承重量有限,装的质数的和不能超过 L。给出 L,请问口袋里能装下几个质数?将这些质数从小往大输出,然后输出最多能装下的质数的个数,数字之间用换行隔开。
输入格式
一行一个正整数 L。
输出格式
将这些质数从小往大输出,然后输出最多能装下的质数个数,所有数字之间有一空行。
输入输出样例
输入 #1
100
输出 #1
2 3 5 7 11 13 17 19 23 9
输入 #2
5
输出 #2
2 3 2
输入 #3
11
输出 #3
2 3 5 3
说明/提示
数据保证,1≤L≤105。
代码如下:
import java.util.Scanner;
// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,
// then press Enter. You can now see whitespace characters in your code.
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int[] a=new int[1001];
int b = scanner.nextInt();
int s=0,s2=0;
for(int i=2;i<=b;i++){
int flag=0;
for(int j=2;j<=Math.pow(i,0.5);j++){
if(i%j==0){
flag=1;
break;
}
}
if(flag==0){
if(s2+i<=b){
s++;
s2+=i;
System.out.println(i);
}else{
System.out.println(s);
break;
}
}
}
if(b==1) System.out.println(s);
}
}