sharptooth
sharptooth

Reputation: 170509

What's the reason for this seemingly overengineered code for checking one number is a multiple of another?

According to this answer if I want to check one number is a multiple of another I can use the remainder operator %.

 if( number % anotherNumber == 0 ) {
    number is a multiple of anotherNumber
 }

Yet in this fun project which is full of intentionally overengineered code they use the following approach:

// int number;
// int anotherNumber;
if ((((int)(number / anotherNumber)) * anotherNumber == number)) {
    number is a multiple of anotherNumber
}

which in effect divides number by anotherNumber and then multiplies it back and checks that the result is number.

Does the second approach have any practical meaning or is it just intentionally overengineered?

Upvotes: 1

Views: 586

Answers (4)

NPE
NPE

Reputation: 500673

It follows directly from the definition of the remainder operator (JLS §15.17.3) that the two are semantically equivalent:

The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.

Therefore, there are no advantages to the more complicated approach.

I can't say why the author wrote it the way they did, but the fact that they felt it necessary to cast the result of integer division to int may give a hint...

Upvotes: 1

MrSmith42
MrSmith42

Reputation: 10151

Example

number = 13
anotherNumber = 4
number / anotherNumber = 13 / 4 = 3.25  // if  number or anotherNumber has type float or double
(int)(number / anotherNumber) = 3
(((int)(number / anotherNumber)) * anotherNumber = 3 * 4 = 12

You can see the result is only the same as number, iff the the devision number / anotherNumber has an integer result.

Therefore

if( number % anotherNumber == 0 ) 

and

if ((((int)(number / anotherNumber)) * anotherNumber == number))

Are true in the same cases. I am quite sure, the first version has better performance.

I am quite sure the programmer who wrote the code, did either not knew about the %-operator, or did not thought about it in this case.

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109597

No, this is clearly a case of less qualifications of the programmer. Modulo one encounters in any computer science course on elementary level. The over-engineering may have followed from similar lack of background/practice.

P.S. I would not underestimate the concerned person.

Upvotes: 0

Marco Forberg
Marco Forberg

Reputation: 2644

looks like the Author of the second code did not know the % operator and uses multiplication to verify if there was a remainder part or not :)

Upvotes: 2

Related Questions