We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Had the same Idea. First tried just iterating through every number in the range but my solution was timing out except for the first 2 and last 2 cases. Then I just noticed that the closest squares (in low ranges) appear always after more than twice the previous perfect square added to the current position (e.g. square 1: 1 + 2*1 = 3, the next square is 4: 4+2*2 = 8, the next square is 9: 9+3*2 = 15, the next square is 16 and so on for 25). By doing this you skip a lot of useless numbers and the solution does't time out.
int main() {
int t;
cin >> t;
for(int a0 = 0; a0 < t; a0++){
int a;
int b;
int count = 0;
cin >> a >> b;
int range;
for(range = a; range <=b; ++range){
int temp = sqrt(range);
if(temp*temp == range)
{
count++;
range += temp*2 ;
}
}
cout<<count<<"\n";
}
return 0;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and Squares
You are viewing a single comment's thread. Return to all comments →
Had the same Idea. First tried just iterating through every number in the range but my solution was timing out except for the first 2 and last 2 cases. Then I just noticed that the closest squares (in low ranges) appear always after more than twice the previous perfect square added to the current position (e.g. square 1: 1 + 2*1 = 3, the next square is 4: 4+2*2 = 8, the next square is 9: 9+3*2 = 15, the next square is 16 and so on for 25). By doing this you skip a lot of useless numbers and the solution does't time out.
}