A perfect square is taken in binary and some bits are replaced with “?” for example 1??, the number would be 4.(or 1????000???0000)
I need to find that perfect square.(there will be only such possible number)
number of ‘?’s in the string be n
To find that number what I am doing is iterating through 2**n numbers(111,110,101,100) and checking if it is a perfect square. I am using following function to check if it is a perfect square.
bool issqr(int n){
int d=(int)(sqrt(n));
if(d*d==n) return true;
else return false;
}
Even though in python I did it, it is taking a lot of time, so I shifted to C++ using only bit operations for populating 2**n numbers(which was much faster than the python version)
but this fails if the number has more than 64 bits
How to avoid this problem? How can I do the same thing if a number has say 120 bits.
(10100110???1?1?01?1?011000?1100?00101000?1?11001101100110001010111?0?1??0110?110?01?1100?1?0110?1?10111?01?0111000?10??101?01)
Rather than re-writing in C++ you should first have looked at improving your algorithm. The lowest possible answer is the square root from the original value with all ‘?’ replace by 0 rounded up, the highest possible answer is the square root of the pattern with the ‘?’s replaced by 1 rounded down. Find those two values, iterate through them, square and check against the pattern.
This is faster both because you are iterating through many fewer numbers and because you aren’t calculating any square roots in the loop: squaring is much easier.
You don’t need to compare string to check for a match:
So putting it all together:
Output:
N.B. This only works in Python 3.x, the last test will overflow
rangein Python 2.x