您的位置:首页 > 编程语言 > C语言/C++

Consecutive k-Primes

2017-06-03 18:54 531 查看

Consecutive k-Primes

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: Given an integer k and a list arr of positive integers the function consec_kprimes (or its variants in other languages) returns how many times in the sequence arr numbers come up twice in a row with exactly k prime factors?

Examples:

arr = [10005, 10030, 10026, 10008, 10016, 10028, 10004]

consec_kprimes(4, arr) => 3 because 10005 and 10030 are consecutive 4-primes, 10030 and 10026 too as well as 10028 and 10004 but 10008 and 10016 are 6-primes.

consec_kprimes(4, [10175, 10185, 10180, 10197]) => 3 because 10175-10185 and 10185- 10180 and 10180-10197 are all consecutive 4-primes.

Note: It could be interesting to begin with: https://www.codewars.com/kata/k-primes

#include <vector>

class PrimeConsec
{
private:
static int countPrimeDiv(long long n)
{
int cnt = 0;
for (int i = 2; i <= n; ++i)
{
while (n >= i)
{
if (n%i == 0)
{
++cnt;
n = n / i;
}
else
break;
}
}
return cnt;

}
public:
static int consecKprimes(int k, std::vector<long long> &arr)
{
int ans = 0;
bool isKprimes = false;
std::for_each(arr.begin(), arr.end(), [k,&ans,&isKprimes](long long ele) {
if (k == countPrimeDiv(ele))
{
if (isKprimes)
{
++ans;
}
isKprimes = true;
}
else
{
isKprimes = false;
}
});
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  codewars c++