Ivars
Ivars

Reputation: 2443

Is it safe to compute remainder by performing division, multiplying back by the divisor, then subtracting the result from the dividend?

int a = 978;
int b = 24;
int c = a - (a / b) * b;

c seems to be remainder of division of a and b but I don't believe that operator % is doing exactly the same. So what's the trick?

Upvotes: 1

Views: 259

Answers (2)

user3424930
user3424930

Reputation: 21

a - (a/b) * b = a % b

c=a%b calculates the remainder of a when divided by b and is stored in c.

Upvotes: 0

Lee White
Lee White

Reputation: 3729

The % operator does actually do exactly that. Your method is safe as long as b != 0, but the same thing goes when using %.

Upvotes: 3

Related Questions