素数筛法+暴力题【点击蓝色字体,查看素数筛法详情!!!】
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();
}
}