在这个问题中,我们给了两个整数L和R。我们的任务是打印已设置位数的总数为L到R之间的质数的总数。
让我们以一个例子来了解问题
Input: L = 7, R = 12 Output: 6 Explanation: 7 -> 111 , set bits = 2, prime number. 8 -> 1000 , set bits = 1, not prime number. 9 -> 1001 , set bits = 2, prime number 10 -> 1010 , set bits = 2, prime number 11 -> 1011, set bits = 3, prime number 12 -> 1100, set bits = 2, prime number
为了解决这个问题,我们将遍历范围内的每个元素。并检查数字中设置位的总数,为此,我们将在CPP _builtin_popcount()中使用预定义的函数。然后,我们将检查数字的设置位是否为素数。如果是,则增加计数,否则不增加。
显示我们解决方案实施情况的程序
#include <iostream> using namespace std; bool isPrimeNumber(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true; } void printPrimeSetBits(int l, int r) { int tot_bit, count = 0; for (int i = l; i <= r; i++) { tot_bit = __builtin_popcount(i); if (isPrimeNumber(tot_bit)) count++; } cout<<count; } int main() { int L = 7, R = 13; cout<<"Total numbers with prime set bits between "<<L<<" and "<<R<<" are : "; printPrimeSetBits(L, R); return 0; }
输出结果
Total numbers with prime set bits between 7 and 13 are : 6