5kyu k-Primes

博客围绕5kyu k-Primes题目展开,介绍了k-prime的定义,包含两个任务,一是完成给定参数返回指定范围内k-prime数组的函数,二是找出满足特定等式的解的总数。还提及题目关键在于计数素因子个数,给出经典因子分解模板思路及最终AC代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

5kyu k-Primes

题目背景:

A natural number is called k-prime if it has exactly k prime factors, counted with multiplicity.

Task:

Complete the function count_Kprimes (or countKprimes, count-K-primes, kPrimes) which is given parameters k, start, end (or nd) and returns an array (or a list or a string depending on the language - see “Solution” and “Sample Tests”) of the k-primes between start (inclusive) and end (inclusive).

Second Task (puzzle):

Given positive integers s, a, b, c where a is1-prime, b is 3-prime, c is 7-prime, find the total number of solutions where a + b + c = s. Call this function puzzle(s).

题目分析:

本道题主要是如何计数素因子的个数,关于计数素数因子个数的方法,存在非常经典的因子分解的模板思路,先附上计数素因子个数的函数:

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的代码:

class KPrimes{
public:
    static std::vector<long long> countKprimes(int k, long long start, long long end);
    static int puzzle(int s);
    static int count_primes(long long num);
};

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;
}

std::vector<long long> KPrimes::countKprimes(int k, long long start, long long end){
    if ( start > end || k < 1 ) return {};
    std::vector<long long> res;
    for ( long long i = start; i <= end; i++) {
        if ( count_primes(i) == k) res.push_back(i);
    }
    return res;
}

int KPrimes::puzzle(int s){
    long long s1 = (long long)s;
    std::vector<long long> one_prime = countKprimes(1, 2, s1);
    std::vector<long long> three_prime = countKprimes(3, 8, s1); // 2 * 2 * 2 = 8
    std::vector<long long> seven_prime = countKprimes(7, 128, s1);
    int res_cnt = 0;

    for ( int cnt_1 = 0; cnt_1 < one_prime.size(); cnt_1++ ) {
        for ( int cnt_3 = 0; cnt_3 < three_prime.size(); cnt_3++ ) {
            long long sum = one_prime[cnt_1] + three_prime[cnt_3];
            if ( std::find(seven_prime.begin(), seven_prime.end(), s1 - sum) != seven_prime.end() ) res_cnt++;
        }
    }
  
    return res_cnt;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值