/**
699 · Check Sum of K Primes
Algorithms
Hard
Accepted Rate
27%
DescriptionSolutionNotesDiscussLeaderboard
Description
Given two numbers n and k. We need to find out if n can be written as sum of k prime numbers.
n <= 10 ^ 9
Example
Example 1
Input:
n = 10
k = 2
Output: true
Explanation: 10 = 5 + 5
Example 2
Input:
n = 2
k = 2
Output: false
Tags
Related Problems
https://blog.csdn.net/weixin_33965305/article/details/88797117
https://www.lintcode.com/problem/699/
*/
/**
* @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.
*/
func isSumOfKPrimes (n int, k int) bool {
// write your code here
if k * 2 > n {
return false
}
if k == 1 {
return isPrime(n)
}
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
}
}
}
func isPrime(n int) bool {
if n < 2 {
return false
} else {
for i := 2; i < n / 2 + 1; i++ {
if n % i == 0 {
return false
}
}
}
return true
}