Some small things that I learned during quarantine

Revision en4, by ronak037, 2020-06-27 18:25:08

Hello guys, I hope you are doing well in this quarantine period. I want to share some small things from which my some question got WA instead of Accepted which needs to be taken care of while coding and I note down those points and also want to share with you. Maybe you already know them and maybe, for someone these are helpful.

  1. When we use pow function then it may give the wrong answer when we are using it for big values so instead, always add some changes while using it like instead of using directly, add 0.5 to it given value and then typecast into it int or long long as per the requirement. Example avoid writing pow(2,20), instead write (long long)(pow(2,20)+0.5). This will surely give the correct result.

[Edit]: please avoid using pow function as discussed in comments. Instead, use the divide and conquer method:

long long power(long long a,long long b)
{
    if(b==0) return 1;
    long long p = power(a, b/2);
    if(b&1) return p*p*a;
    else return p*p;
}
  1. Don't use sqrt function in a loop for comparison like this for(int i = 0; i <= sqrt(n); i++){} but precalculate the value of sqrt(n) and store it in different variable then use it in for loop. This is because if you don't precalculate the value then it may give TLE because every time loop will execute then every time it calculates sqrt(n).

  2. When we use v.size() for vector so this gives runtime error once in my solution because maybe I subtract some bigger value from its returned value which I didn't able to know during the contest then someone told me that .size() return unsigned long long value due to which this happens so from onwards I always start to typecast it into long long also such that that type of error will not come again. This is that solution: link

  3. Always typecast first value into a long double then use it in log function because otherwise, it may give the wrong answer due to some precision error in big values. Use log like this log((log double)z).

[Edit]: Instead of typecase you can also directly use logl function which automatically typecast and help to find the desired output.

These are some things that I learned during this quarantine period and this seems very small mistakes but very difficult to debug.

Thanks to all and also welcome other tips and suggestions. And please correct me if I am wrong somewhere.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en4 English ronak037 2020-06-27 18:25:08 159
en3 English ronak037 2020-06-27 18:20:37 270
en2 English ronak037 2020-06-27 15:27:28 36
en1 English ronak037 2020-06-27 15:23:34 2088 Initial revision (published)