Optimizing code for UVAJ 573 The Snail I'm getting the right results for the code for the sample outputs, but the OJ is giving a TLE (3 seconds max).

The questions is here.

int main()
{
    double h,u,d,f;
    while(scanf("%lf%lf%lf%lf",&amp;h,&amp;u,&amp;d,&amp;f)!=EOF)
    {
        //cin&gt;&gt;h;
       // if(h==0)
          //  break;
        //cin&gt;&gt;u&gt;&gt;d&gt;&gt;f;
        double fu=.01*f*u;
        double used_fu=0;
        int day=1;
        double crossed=0;
        int success=0;
        while(1)
        {
            crossed+=(u-used_fu);
            if(crossed&gt;h)
            {
                success++;break;
            }
            crossed-=d;
            if(crossed&lt;0)
                break;
            used_fu+=fu;
            day++;
        }
        if(success==0)
            cout&lt;&lt;"failure";
        else
            cout&lt;&lt;"success";
        cout&lt;&lt;" on day "&lt;&lt;day&lt;&lt;"\n";
    }
    return 0;
}
So first things first, your code looks terrible.


Use real names for your variables that are understandable without any further reading, e.g. instead of fu you could use fatique.
Your variable success is a boolean so make it one.
You should introduce a factor for the fatique rather than subtracting it. That would make the code simpler. Also your failure is most likely because the snail takes so much time to slide back down. So rather than checking for snailHeight &gt; 0 check for heightSlid &gt; fatique * heightClimbed

size_t numDays = 0;
double snailHeight = 0.0;
double fatique = 1.0;
bool fail = false;
while (true) {
    numDays++;
    snailHeight += fatique * heightClimbed;
    fatique *= 0.9;
    if (heightSlid &gt; fatique * heightClimbed) {
        fail = true;
        break;
    } else if (snailHeight &gt; heightWell) {
        break;
    }

    snailHeight -= heightSlid;
}

if (fail) {
    std::cout &lt;&lt; "failure\n";
} else {
    std::cout &lt;&lt; "success on day " &lt;&lt; numDays &lt;&lt; "\n";
}