c++ - Not able to figure out how the code can be further optimised -
this problem hackerrank , link : https://www.hackerrank.com/challenges/sherlock-and-squares . program below prints count of numbers perfect squares within given range. however, error of time limit exceeded constraints testcases 1 < testcase < 100
, 2 integers in range 1 < number 1 < 10^9, 1 < number2 < 10^9
.
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include<math.h> using namespace std; int main() { /* enter code here. read input stdin. print output stdout */ int testcase; cin>>testcase; //input testcase while(testcase--) { int number1,number2,count=0; cin>>number1>>number2; //input limits for(int i=number1;i<=number2;i++) //check each number within limits if proper square { if(sqrt(i)==floor(sqrt(i))) count++; } cout<<count<<endl; //print total count of numbers perfect square within limits } return 0; }
can please tell me how optimize problem further. not able figure out how time complexity can further reduced.
i'm not going code you. :
instead of testing every number, find first perfect square in range. then, increment 1 square root of perfect square. gives next perfect square. repeat until reach upper limit.
expected improvement around order of numbers. if number1 1000, you'll skipping around thousand number @ each step. should pass easily.
Comments
Post a Comment