Jeremy Shanks
Jeremy Shanks

Reputation: 33

Am I performing my order of operations incorrectly in Java?

I'm having a bit of trouble with this question.

I'm unsure where % (mod) sits on the BEDMAS order of operations.

37 % 20 % 3 * 4 = ?

My mental arithmetic answer is 5 but I must be doing something wrong. Where does % mod sit within BEDMAS?

Upvotes: 3

Views: 131

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109547

BEDMAS is misleading as it suggests Division before Multiplication. It is more something for primary school.

It should be

  1. multiplicative operations: * / %
  2. additive (binary) operations: + -

Brackets, unary (-), bits and logic operations not entirely covered by BEDMAS too.

    (((37 % 20) % 3) * 4) = 8

And not Multiplication after Modulo:

    ((37 % 20) % (3 * 4)) = 5  ***

Upvotes: 4

Helight Development
Helight Development

Reputation: 39

I just tested this and java outputs the exactly right result. 37 % 20 = 17, 17 % 3 = 2, 2 * 4 = 8. But refer to MathExchange for your BEDMAS question

Upvotes: 1

Mureinik
Mureinik

Reputation: 311163

The modulu (%) operator has the same precedence as the division (/) operator, so:

37 % 20 is 17
17 % 3 is 2
2 * 4 is 8

IDEOne output

Upvotes: 8

Related Questions