• + 13 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.

    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;
    

    }