I am an amateur programmer and I tried coding this problem using the TurboC++ IDE (though my code is in C), but the site's compiler throws a "TIME LIMIT EXCEEDED" error. How can I optimize my code further?

int main()
    long int n,j,k,sqt,tot,t,i,c;

        scanf("%ld",&n); tot=n;
                { if(((long)sqrt(j)*(long)sqrt(j)!=j))
                else {c++;break; }
            if(tot==0)  {printf("%ld\n",k);break;}

    return 0;

Please do tell me if the code is wrong.

  • \$\begingroup\$ Have you tried your code on some sample inputs? Does it seem to work? \$\endgroup\$ – svick Jun 6 '13 at 13:54
  • \$\begingroup\$ @svick yes it does work for all those that i tried \$\endgroup\$ – ragsvds Jun 6 '13 at 14:17
  1. You need to pre-calculate all square-free integers below the greatest in input (in test it's 100) and don't calculate that for every input value.
  2. You need a very fast precalculation algorithm like a modified Sieve of Eratosthenes.
  3. Don't forget about the time limit - it's 8 sec. only (and not on the top hardware, I assume). Benchmark your code using the following testcase:

  4. If you want to find past solutions, take it here.

  5. If you want to see the explanation, read this topcoder editorial about the problem SquareFree.
| improve this answer | |
  • \$\begingroup\$ thanks a lot for ur response and for introducing me to the Sieve of Eratosthenes. \$\endgroup\$ – ragsvds Jun 6 '13 at 14:20
  • \$\begingroup\$ and thanks for taking the trouble to find all this... \$\endgroup\$ – ragsvds Jun 6 '13 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.