Search code examples
c++divisionmodulusfloor

efficient way to divide ignoring rest


there are 2 ways i found to get a whole number from a division in c++

question is which way is more efficient (more speedy)

first way:

Quotient = value1 / value2;  // normal division haveing splitted number

floor(Quotient);             // rounding the number down to the first integer

second way:

Rest = value1 % value2;             // getting the Rest with modulus % operator

Quotient = (value1-Rest) / value2;  // substracting the Rest so the division will match

also please demonstrate how to find out which method is faster


Solution

  • If you're dealing with integers, then the usual way is

    Quotient = value1 / value2;
    

    That's it. The result is already an integer. No need to use the floor(Quotient); statement. It has no effect anyway. You would want to use Quotient = floor(Quotient); if it was needed.

    If you have floating point numbers, then the second method won't work at all, as % is only defined for integers. But what does it mean to get a whole number from a division of real numbers? What integer do you get when you divide 8.5 by 3.2? Does it ever make sense to ask this question?

    As a side note, the thing you call 'Rest' is normally called 'reminder'.remainder.