6kyu Steps in k-primes
题目背景:
A natural number is called k-prime if it has exactly k
prime factors, counted with multiplicity.
Task:
We will write a function kprimes_step(k, step, start, nd)
with parameters:
k
(integer > 0) which indicates the type of k-primes we are looking for,step
(integer > 0) which indicates thestep
we want to find between two k-primes,start
(integer >= 0) which gives the start of the search (start inclusive),nd
(integer >= start) which gives the end of the search (nd inclusive)
题目分析:
本道题主要是 如何计数素因子的个数,关于计数素数因子个数的方法,存在非常经典的因子分解的模板思路,先附上计数素数个 数的函数:
int KPrimes::count_primes(long long num){
long long i = 2;
int cnt = 0;
while( i * i <= num ) {
while( num % i == 0 ) {
num /= i;
cnt++;
}
i++;
}
if ( num != 1 ) cnt++;
return cnt;
}
最终AC的代码:
#include <vector>
namespace KStep{
int count_primes(long long num){
long long i = 2;
int cnt = 0;
while( i * i <= num ) {
while( num % i == 0 ) {
num /= i;
cnt++;
}
i++;
}
if ( num != 1 ) cnt++;
return cnt;
}
std::vector<std::pair <long, long>> kprimesStep(int k, int step, long long m, long long n){
if ( k < 1 || m > n || step < 1 ) return {};
std::vector<std::pair <long, long>> res;
for ( long long i = m; i <= n - step; i++) {
if ( count_primes(i) == k && count_primes(i + step) == k) {
std::pair <long, long> seg = std::make_pair ( i, i + step );
res.push_back(seg);
}
}
return res;
}
}