0
How can I reduce the time of compilation?
I did the task but it has to compile less than 1 second? How can I do it? Here is the code! https://code.sololearn.com/cM7ZJl4Yt6hP/?ref=app
3 Answers
+ 1
Okay, that means that the range between a and b can get quite high and that you need to get rid of the loop.
There is probably some nice algorithm about that can solve your problem with ease; maybe something like Gauss formula.
But I think we can figure something out without looking it up. It is quite easy to see that, if you add/subtract the numbers successively there is some kind of pattern:
a = 4
b = 7
result = 4 - 5 + 6 - 7 = -2
a = 3
b = 6
result = -3 +4 -5 + 6 = 2
a = 4
b = 8
result = 4 - 5 + 6 - 7 + 8 = -2 + 8 = 6
a = 3
b = 7
result = -3 + 4 - 5 + 6 - 7 = 2 - 7 = - 5
We can see that there are actually four different cases that depend on the start/stop-numbers being even or odd:
if a is even and b is odd:
return (b - a +1) /(- 2)
if a is odd and b is even:
return (b -a + 1) /(2)
if a is even and b is even
return (b-a)/(- 2) + b
if a is odd and b is odd
return (b -a) /(2) - b
This should calculate the result fast enough to beat your time limit because the number of calculations does not depend on the difference between a and b. Now you "only" got to implement it in c++. ;-)
+ 2
It should compile pretty fast but you also mean that it needs to run faster, right?
0
Thoq! yes man