P5723 【深基4.例13】质数口袋---java


小A 有一个质数口袋,里面可以装各个质数。他从 2 开始,依次判断各个自然数是不是质数,如果是质数就会把这个数字装入口袋。口袋的负载量就是口袋里的所有数字之和。但是口袋的承重量有限,不能装得下总和超过 L(1≤L≤100000)L(1\le L\le100000)L(1≤L≤100000) 的质数。给出 LLL,请问口袋里能装下几个质数?将这些质数从小往大输出,然后输出最多能装下的质数个数,所有数字之间有一空行。
输入格式

无
输出格式

无
输入输出样例
输入 #1

100

输出 #1

2
3
5
7
11
13
17
19
23
9
import java.util.Scanner;

public class P5723 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int sum = 0;
        int count = 0;
        for (int j = 2; ; j++) {
            if (f(j) == true) {
                sum += j;
                if (sum > n) {
                    break;
                } else {
                    count++;
                    System.out.println(j);
                }
            }
        }
        System.out.print(count);
    }


    public static boolean f(int x) {
        if (x < 2)
            return false;
        if (x == 2)
            return true;
        if (x % 2 == 0)
            return false;
        for (int i = 3; i * i <= x; i += 2) {
            if (x % i == 0)
                return false;
        }
        return true;
    }
}

发布了31 篇原创文章 · 获赞 1 · 访问量 173

猜你喜欢

转载自blog.csdn.net/weixin_44048403/article/details/105384788