Long back in our college, we had a hiring challenge from a certain company that aksed us to solve this :
" Count the number of integers in a given range [l, r] that have prime number of set bits.
(Like 5 => 101 has 2 bits set and 2 is prime so it will counted and so on)
l, r can go up to 10^18
Time limit : 1 second
I do not remember if r-l < 1e6 or not but if not, how to approach this problem
Before I trigger any of you good people , yes I have first googled and I’ve had a look at the geeks for geeks implementation and the similar leetcode question, both of which apply normal brute force.
I have thought of this : since the no of prime number of set bits is small even in that huge range, find the resulting combinations and add
For some context , suppose n is between 0-10 we know that
0000 - 0 set bits
0001 - 1 set bit
0010 - 1 set bits
0011 - 2 set bits +1
0100 - 1 set bits
0101 - 2 set bits +1
0110 - 2 set bits +1
0111 - 3 set bits +1
1000 - 1 set bits
1001 - 2 set bits +1
1010 - 2 set bits +1
My small noob takeaways / thoughts
Now we notice two things, from 1-10 we can have only prime nos { 2 , 3 } so can something be done like enumerating the nos that have 2 ones
Here 5 numbers have 2 ones
And finding numbers that have 3 ones, here 1 number has 3 set bits and summing all the combinations together so is this approach feasible?
I coded the brute force and I am not sure if the numbers 3,5,6,7,9,10 they look like they follow a pattern , which leads me to my next question, how do I know fast if it’s a pattern oriented question
Now I know that the bits follow a pattern like lsb will be 0,1,0,1… and next left bit will be 0,0,1,1… and so on
I had all these ideas running in my head when this challenge happened, it was for 2 I think and there were 2-3 questions, I couldn’t implement any of my ideas and none of them came to fruition and I tanked pretty badly. I’m used to long here where we have days to think and come to an amazing conclusion after loads of efforts, have to work on my short contests.
Are any of these ideas in the right direction!
Now, lastly I’m sorry to subject you all to this huge essay but I thought it would be better if I described what effort I’d taken and where I stand in my train of thought and not simply fishing for solutions as an easy way out.
Approach, suggestions and criticisms are very welcome