[LintCode/LeetCode] Check Sum of K Primes

linspiration發表於2019-01-19

Problem

Given two numbers n and k. We need to find out if n can be written as sum of k prime numbers.

Example

Given n = 10, k = 2
Return true // 10 = 5 + 5

Given n = 2, k = 2
Return false

Solution

public class Solution {
    /**
     * @param n: an int
     * @param k: an int
     * @return: if N can be expressed in the form of sum of K primes, return true; otherwise, return false.
     */
     //https://blog.csdn.net/zhaohengchuan/article/details/78673665
    public boolean isSumOfKPrimes(int n, int k) {
        // write your code here
        if (k*2 > n) return false; //the minumum prime is 2, so is impossible
        if (k == 1) return isPrime(n); //has to be prime itself
        
        // Based on: any even number is the sum of an even number of primes!
        if (k%2 == 1) {
            if (n%2 == 1) return isSumOfKPrimes(n-3, k-1);
            else return isSumOfKPrimes(n-2, k-1);
        } else {
            if (n%2 == 1) return isSumOfKPrimes(n-2, k-1);
            else return true;
        }
    }
    private boolean isPrime(int n) {
        if (n < 2) return false;
        else {
            for (int i = 2; i < n/2+1; i++) {
                if (n%i == 0) return false;
            }
        }
        return true;
    }
}

相關文章