ในปัญหานี้ เราได้รับสองจำนวนเต็ม 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