Problem 77
Prime summations
It is possible to write ten as the sum of primes in exactly five different ways:
7 + 3
5 + 5
5 + 3 + 2
3 + 3 + 2 + 2
2 + 2 + 2 + 2 + 2
What is the first value which can be written as the sum of primes in over five thousand different ways?
素数加和
将10写成素数的和有5种不同的方式:
7 + 3
5 + 5
5 + 3 + 2
3 + 3 + 2 + 2
2 + 2 + 2 + 2 + 2
写成素数的和有超过五千种不同的方式的数最小是多少?
package projecteuler;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
public class Prj77 extends TestCase {
public static final int UP_LIMIT = 5000;
public void testPrimeSummations() {
List<Integer> primeList = new ArrayList<Integer>();
primeList.add(2);
primeList.add(3);
primeList.add(5);
primeList.add(7);
for (int i = 8;; i++) {
if (isPrime(i)) {
primeList.add(i);
}
if( iterCount( list2Arr(primeList), i, primeList.size()) > UP_LIMIT){
System.out.println("i=" + i);
break;
}
}
}
public void testIterCount() {
int[] arr = new int[] { 1, 2, 5, 10 };
int num = 100;
int n = iterCount(arr, num, arr.length);
System.out.println("n=" + n);
}
private int[] list2Arr(List<Integer> primeList) {
int[] ret = new int[primeList.size()];
for(int i = 0 ; i < ret.length; i ++){
ret[i] = primeList.get(i);
}
return ret;
}
private boolean isPrime(int num) {
if (num <= 10) {
if (num == 2 || num == 3 || num == 5 || num == 7) {
return true;
}
return false;
}
if (num % 2 == 0) {
return false;
}
for (int i = 3; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public int iterCount(int[] arr, int num, int n) {
if (num == 0) {
return 1;
}
if (num < 0 || n <= 0) {
return 0;
}
return iterCount(arr, num - arr[n - 1], n) + iterCount(arr, num, n - 1);
}
}