Project Euler #77: Prime summations 回溯法得不到满分

Problem Statement

This problem is a programming version of Problem 77 from projecteuler.net

It is possible to write ten as the sum of primes in exactly five different ways:

7+35+55+3+23+3+2+22+2+2+2+2

You are given  N , in how many ways can  N  be written as sum of 1 or more primes?

Input Format 
First line of the input contains  T , which is number of testcases. 
Each testcase contains  N .

Constraints 
1T100  
2N1000

Output Format 
Print the output corresponding to each testcase on a new line.

Sample Input

2
5
10

Sample Output

2
5
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    private static long num=0;
    public static boolean isPrime(int n){
        for(int i=2;i<=Math.sqrt(n);i++){
            if(n%i==0)
                return false;
        }
        return true;
    }
    
    public static void divideNum(int start,int n,int sum){
        if(n==sum){
            num++;
        }
        else{
            for(int i=start;i<=n-sum;i++){
                if(isPrime(i)){
                    sum+=i;
                    divideNum(i,n,sum);
                    sum-=i;
                }
            }
        }
    }

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner cin=new Scanner(System.in);
        int m=cin.nextInt();
        
        while(m--!=0){
            int n=cin.nextInt();
            num=0;
            divideNum(2,n,0);
            
            System.out.println(num);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值