vector<int> primes = generatePrimes(MAX_LIMIT);
int n = primes.size();
int tc;
cin >> tc;
while (tc--) {
int h;
cin >> h;
int ans = INT_MAX;
if (h >= 2 && isSumOfPowersOf2(h)) {
ans = __builtin_popcount(h);
}
if (h >= 2) {
int ind = upper_bound(primes.begin(), primes.end(), h) - primes.begin();
if (ind == n)
ind--;
for (int i = ind - 1; i >= 0; i--) {
if (primes[i] <= h) {
int num = h - primes[i];
if ((num & (num + 1)) == 0) {
int jumps = __builtin_popcount(num) + 1;
ans = min(jumps, ans);
}
}
}
} else {
ans = -1; // Unable to kill the monster
}
ans!=INT_MAX?cout << ans << endl:cout<<-1<<endl;
}
return 0;
Generate all Prime Numbers (as Here Health 1≤H≤10^6)
Now To Reduce Health To Zero We Have Two Options Either Reduced By Power of 2 (First By 2^0,2^1,…) or Reduce Prime Number From Health H.
So I Decided That Let’s First Check Whether Number’s all Bit are Set Or Not.If Yes Then We Can Reduce That Health By Substracting Power of 2.
Now Question Aries that How Much Operaions Needed That Will Be Equivalent to Number of Set Bit In Number.
Later I Try All The Prime Number Which is Less than Or Equal to Given Health and Whatever Number Comes After Substracting Prime Number From H, I Checked Whether That Number is Also SUm of Power of 2.
I Checked For all Prime Numbers Less Than Health H.Minimum of Them is Stored in ans.
Yah thats why you should think how complex and lengthy it would to genrate all the prime numbers if you were given a large number …Your logic is right but try making it optimal and efficient.
Also working into binary number is not always faster and better