Why both code having same logic don't work? [SUBPRNJL]

ceil
modulo
subprnjl

#1

I got WA when used

m = ceil((float(k)/float(r-l+1));

but got AC when used

m = k/(r-l+1) + k%(r-l+1)==0?0:1;

Can somebody tell me the difference between the two?

My submission using both:

https://www.codechef.com/viewsolution/23444985 - using ceiling function
https://www.codechef.com/viewsolution/23444732 - using ternary operator


#2

Let k=8, (r-l+1)=3

Then the first value of m is 4. While the second line checks whether 8/3 + 8%3 == 0, which simplifies to 4==0.
I haven’t seen the rest of your code, but this observation might help you.


#3

float type is single-precision floating point and it has significand precision of 24 bits. This means that it cannot accurately represent integers above 2^{24}, which is much lower than the maximum value of k which is 10^9. This introduces an error in your ceil calculation.

An easy way to compute ceil(a / b) for integers a, b without involving floats is (a + b - 1) / b.


#4

the value of m in 1st is 3, ceil(8/3)=ceil(2.6)=3
You calculated wrong.


#5

Thank you tried with with long double and it worked and also thanks for the tip for calculating ceil function. Much appreciated.


#6

Loved the (a+b-1)/b tip!