5kyu k-Primes
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 = 8std::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; }總結
以上是生活随笔為你收集整理的5kyu k-Primes的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 6kyu Steps in k-prim
- 下一篇: 6kyu Build a pile of