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; } };
相关文章推荐
- UVa Problem Solution: 10168 - Summation of Four Primes
- UVA 10236 The Fibonacci Primes
- poj 3978 Primes
- B. T-primes
- (Problem 35)Circular primes
- hdu 4715 Difference Between Primes(stl)
- Difference Between Primes
- 【PAT Advanced Level】1015. Reversible Primes (20)
- (Problem 35)Circular primes
- Problem 10:Summation of primes
- 237C - Primes on Interval
- zoj 2822 - Sum of Different Primes
- USACO6.4-The Primes
- * SPOJ PGCD Primes in GCD Table (需要自己推线性筛函数,好题)
- [LeetCode] Count Primes 质数的个数
- Leetcode204-Count Primes
- Count Primes
- SGU 102. Coprimes
- LeetCode | Count Primes
- Project Euler:Problem 47 Distinct primes factors