 # how can i make this code any faster?

How can I make this code any faster? Right now it is exceeding the time limit of 2 seconds.

Help would be greatly appreciated.

Here’s the question: http://www.codechef.com/problems/SDSQUARE

``````#include <iostream>
#include <math.h>

using namespace std;

bool check(int num){ // Check if number is consisted of all squares
int temp;
while (num > 0){
temp = num % 10;
if (temp != 0 && temp != 1 && temp != 4 && temp != 9){
return false;
}
num /= 10;
}
return true;
}

int main() {
int t, a, b, i;
cin >> t;
while (t--){
i = 0;
cin >> a >> b;
int l = floor(sqrt(a));
int r = pow(l, 2);
while (r <= b){
if (check(r) == true){ // Check if square is made of "perfect digits"
i++; // Increment the count of perfect digit squares
}
r += 2 * l + 1; // Find next square
l++; // Increment the square root
}
cout << i << endl;
}
}
``````

You can store these perfect squares instead of computing and checking for every single one. And then you can easily find the number of perfect squares between a & b.

View Solution–>>
http://www.codechef.com/viewsolution/2927572

@shanman: U can also implement fast I/O in ur solution to make it faster Only way to make this faster is Store all perfect square. Then try to find out some way to use this collection effectively.

You Can see my solution also here

Ask me if you find any difficulties to understand

Happy coding

//