How modulus works?

Alles, was PHP betrifft, kann hier besprochen werden.

How modulus works?

Hi,

Good day to you.

I have been searching information about modulus for days but I found that they all gave different answers (from my opinion .....)

Code: Select all

\$a % \$b
Basically, the defination is the remainder when you divide \$a by \$b.

1) First example from website
Code: Select all

"what if you take 7/5? If you plug this into the PHP engine, you'll get a decimal number of 1.4. However, if you do 7 modulus 5, you're going to get 2."

I think I can understand this, the result is rounded up to the nearest integer to 2.

2) Second example from book.
Code: Select all

"27 % 10, answer is 7."

I failed to understand why 27 / 10 and the remainder is 7. Shouldn't it be 2.7 ? Even if it rounds to nearest integer, it should be 2 or 3.

3) Third exmaple from tizag
Code: Select all

"Perform modulus: 5 % 2 = 1. Modulus is the remainder after the division operation has been performed. In this case it was 5 / 2, which has a remainder of 1. "

Again, after dividing 5 by 2, it should be 2.5, how it becomes 1?

I wish to get some advice from you.
Thank you.
dennisl

Posts: 10
Joined: 06. July 2009 11:23

Re: How modulus works?

Code: Select all
"27 % 10, answer is 7."

Modulo is defined as:
Code: Select all
(a mod m) = a - m * (a div m)

(the result of "a div m" is converted to an integer (round down to zero))

Example
Code: Select all
(27 mod 10) = 27 - 10 x (27 div 10)
(27 mod 10) = 27 - 10 x (2)          // 27 : 10 = 2.7; (int) 2.7 = 2
(27 mod 10) = 27 - 20
(27 mod 10) = 7
Wiedmann
AF Moderator

Posts: 17106
Joined: 01. February 2004 12:38
Location: Stuttgart / Germany

Re: How modulus works?

Or to make Wiedmann's Post short: You subtract the second number as often as possible from the first number. What remains is your result. Example:

27 mod 8:

Code: Select all
27 - 8 = 19
19 - 8 = 11
11 - 8 = 3

That means: 27 mod 8 = 3

glitzi

glitzi85

Posts: 1920
Joined: 05. March 2004 23:26
Location: Dahoim

Return to PHP

Who is online

Users browsing this forum: No registered users and 2 guests