Project Euler 77:Prime summations

时间:2022-11-30 03:16:16

原题:

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

写成素数的和有超过五千种不同的方式的数最小是多少?

思路:

动态规划题目

我直接网上找的代码

但是大家写的好多都一样的

附:之前的动态规划介绍

Java程序:

package Level3;

import java.util.ArrayList;
import java.util.Iterator; public class PE077 { void run(){
int limit = 5000;
dp(limit);
} void dp(int limit){
ArrayList<Integer> plist = listPrime(limit/5);
int target = 2;
while(true){
int[] ways = new int[target+1];
ways[0] = 1;
for(int i=0;i<plist.size();i++){
for(int j=(int) plist.get(i);j<=target;j++)
ways[j] += ways[j-(int) plist.get(i)];
}
// System.out.println(target+" " + ways[target]);
if(ways[target] > limit) break;
target++;
}
System.out.println(target); }
// 71
// running time=0s7ms
ArrayList<Integer> listPrime(int limit){
int prime[] = new int[limit];
ArrayList<Integer> plist = new ArrayList<Integer>();
boolean isPrime = true;
prime[0]=2;
plist.add(2);
int p=1;
for(int i=2;i<limit;i++){
isPrime = true;
Iterator<Integer> it = plist.iterator();
while(it.hasNext() &&isPrime){
int prm=it.next();
if(i%prm==0){// 说明 i 不是素数
isPrime = false;
break;
}
} if(isPrime==true)
plist.add(i);
} return plist; } public static void main(String[] args) {
long t0 = System.currentTimeMillis();
new PE077().run();
long t1 = System.currentTimeMillis();
long t = t1 - t0;
System.out.println("running time="+t/1000+"s"+t%1000+"ms");
} }

Python程序:

import time 

def sieve(limit):
primes= []
is_prime = True
primes.append(2)
for i in range(3,limit):
is_prime = True
for ps in primes:
if i%ps ==0:
is_prime = False
break
if is_prime==True:
primes.append(i)
return primes def dp(limit):
primes = sieve(1000)
target = 2
while True:
ways = [1] + [0]*target
for prime in primes:
for j in range(prime,target+1):
ways[j] += ways[j-prime]
if ways[target]> limit:
break
target+=1
print target
#
# running time 0.00999999046326 s
if __name__=='__main__':
t0 = time.time()
limit = 5000
dp(limit)
print"running time",(time.time() - t0),"s"