Due to floating-point rounding, your code computes ans
to be 26,234.999999999985448084771633148193359375. When it is printed with cout<<ans
, the default formatting does not show the full value and rounds it to “26235”. However, when the actual value is converted to int
, the result is 26,234.
After setting num
to m+n-2
, your code is computing num
! / ((m-1
)!(num-m+1
)!), which of course equals num
! / ((num-m+1
)!(m-1
)!). Thus, you can use either m-1
or num-m+1
as the limit. So you can change the while
line to these two lines:
int limit = m-1 < num-m+1 ? m-1 : num-m+1;
while(den<=limit) {
and then your code will run to the lower limit, which will avoid dividing ans
by factors that are not yet in it. All results will be exact integer results, with no rounding errors, unless you try to calculate a result that exceeds the range of your double
format where it is able to represent all integers (up to 253 in the ubiquitous IEEE-754 binary64 format used for double
).