POJ 2739(Sum of Consecutive Prime Numbers) 素数筛法+暴力 Java

素数筛法+暴力题【点击蓝色字体,查看素数筛法详情!!!】

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * 题意:寻找连续的素数之和等于 inputNum 的素数组有多少组? 
 *      如:素数和=41的有3组 41=41、41=11+13+17、41=2+3+5+7+11+13。
 * 
 * 分析:线性素数筛法+暴力遍历即可
 * 
 * @author TinyDolphin
 *
 */
public class Main {

    private static final int LENGTH_CHECK = 13000;
    private static final int LENGTH_PRIMELIST = 1300;

    private static boolean[] check = new boolean[LENGTH_CHECK];
    private static int[] primeList = new int[LENGTH_PRIMELIST];

    // 常规的欧拉筛法
    private static void getPrimeList(int num) {
        int count = 0;
        for (int indexI = 2; indexI < num; indexI++) {
            if (!check[indexI]) {
                primeList[count++] = indexI;
            }
            for (int indexJ = 0; indexJ < count; indexJ++) {
                if (indexI * primeList[indexJ] >= num) {
                    break;
                }
                check[indexI * primeList[indexJ]] = true;
                if (indexI % primeList[indexJ] == 0) {
                    break;
                }
            }
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        getPrimeList(10010); // 数组使用长度只有 1229,所以数组长度,开的稍大即可。
        int inputNum;
        while ((inputNum = in.nextInt()) != 0) {
            int sum;
            int count = 0;
            // 暴力遍历即可
            for (int indexI = 0; primeList[indexI] <= inputNum; indexI++) {
                sum = 0;
                for (int indexJ = indexI;; indexJ++) {
                    sum += primeList[indexJ];
                    if (sum == inputNum) {
                        count++;
                    }
                    if (sum >= inputNum) {
                        sum = 0;
                        break;
                    }
                }
            }
            out.println(count);
        }
        out.flush();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值