The oldest problem about a snail (in C ++):

The snail crawls along a vertical pole with a height of h meters, climbing a meter in a day, and going b meters in a night. On which day will the snail crawl to the top of the pole?

The program receives natural numbers h, a, b as input and should output one natural number. It is guaranteed that a> b.

At the decision of this task it is impossible to use the conditional instruction if and cycles.

There is a solution, but I cannot understand it. Can you explain in detail what and how?


1 + h0 / shag + (h0% shag + shag - 1) / shag)

  • (((h - a) + b) / (a - b)) - (a - b) ; Will the answer be correct? - Max Skripkin

2 answers 2

This is an elementary task that is often found at school computer science competitions (grades 7-8!). It is solved by finding a simple formula:

UPD: Thanks to the @avp user who found a fatal error in my old code =)

Corrected version:

 double a = 5, b = 4, h = 1; double days = ((ha)>=0) ? ha:0; days = ceil(days/(ab))+1; cout<<days<<endl; 
  • 3
    @Asen, and you checked? Wrong, with h = 1, a = 5, b = 4; The answer is -3.000000. But do not worry, the second option (1 + h0 / shag + (h0% shag + shag-1) / shag in integers (c double it, of course, does not compile)) gives the same result. - The question remained unanswered, I join the TC in the lack of understanding of such formulas. @ablay, someone deceived you, tell him about it. - Interestingly, the plusies simply unconditionally believe the respondents? - avp
  • @avp, and true Fail is obtained in this situation ... Thank you for saying. Code corrected. --- I checked the code, of course! Just for some reason did not bother to check with "abnormal parameters" =) - Salivan
  h0 = h - a; 

the entire height of the pole minus the distance per day = how many days are needed in the ideal case, i.e. without it slipping

shag = a - b;

how much actually creeps per day

1 + h0 / shag + (h0% shag + shag-1) / shag

a formula that considers what you need =)

  • to Gotets: >> a formula that considers what you need =) here's the formula I can't understand .. - ablay
  • disassemble it in parts, 1 + h0 - in order to withdraw one day if it is enough to lift .. and so on .. - Gorets