A natural number is called k-prime if it has exactly k prime factors, counted with multiplicity.
A natural number is thus prime if and only if it is 1-prime.
Examples:
k = 2 -> 4, 6, 9, 10, 14, 15, 21, 22, …
k = 3 -> 8, 12, 18, 20, 27, 28, 30, …
k = 5 -> 32, 48, 72, 80, 108, 112, …
#Task:
- Write function
count_Kprimes (or countKprimes or count-K-primes or kPrimes)
which given parametersk, start, end (or nd)
returns an array (or a list or a string depending on the language - see "Solution" and "Sample Tests") of thek-primes
betweenstart (inclusive)
andend (inclusive)
.
#Example:
countKprimes(5, 500, 600) --> [500, 520, 552, 567, 588, 592, 594]
...............................................................................
- for all languages except Bash shell
Given positive integers s
and a, b, c
where a is 1-prime
, b 3-prime
, c 7-prime
find the number of solutionsof a + b + c = s
. Call this function puzzle(s)
.
Examples:
puzzle(138) --> 1 ([2 + 8 + 128] is solution)
puzzle(143) --> 2 ([3 + 12 + 128, 7 + 8 + 128] are solutions)
大意:
countKprimes(k,start,end)取出范围内所有拥有K个因数的数
puzzle(s)求出一组分别为1,3,7个因数的数相加之和为s
话不多说贴代码
package solution.codewars;
import java.util.ArrayList;
import java.util.List;
public class KPrimes {
public static long[] countKprimes(int k, long start, long end) {
// your code
List<Long> ret = new ArrayList<>();
for (long i = start;i < end;i ++)
{
List perList = selectFactor(i);
if (perList.size() == k)
{
ret.add(i);
}
}
long[] out = new long[ret.size()];
int count = 0;
for (Object e : ret) {
out[count] = (long)e;
count++;
}
return out;
}
public static int puzzle(int s) {
// your code
return 1;
}
private static boolean judge(long n) {
int j = 2;
if(n < 2)
{
return true;
}
while(j <= n / 2) {
if(n % j == 0)
break;
j ++;
}
if(j == n / 2 + 1) {
return true;
}
return false;
}
private static List selectFactor(long num) {
List<Long> factorNum = new ArrayList<>();
long j;
double temp = num;
if(!judge((int)temp)) {
for(j = 2;temp>0;j ++) {
if(judge(j)) {
if((temp / j) != (int)(temp / j))
continue;
temp /= j;
factorNum.add(j);
if(temp == 1)
break;
j --;
}
}
}
return factorNum;
}
}
puzzle待解决吧= =,思路目前是遍历三个因数的数组,加起来为s的输出