Modulo operations (MoD) and remainder (REM) operations cannot be confused

Source: Internet
Author: User
Tags python script

Typically, modulo operations (MoD) and remainder (REM) operations are confused, because in most programming languages, the '% ' notation is used to represent modulo or remainder operations. Here we want to remind you to pay attention to the specific meaning of the '% ' operator in the current environment, because in the case of negative numbers, the results are different.


For integer number A,b, the method of modulo operation or remainder operation is:

1. Find the integer quotient: c = A/b;

2. Computational model or remainder: R = a-c*b.


The modulo and remainder operations are different in the first step : Modulus- seeking operations are rounded to the 0 direction (fix () function) when the value of C is taken , and the remainder modulo operation rounds in an infinitesimal direction when calculating the value of C (floor ()).

For example: The remainder is -3/4 the result is c=0, but when taken: -3/4 The result is: C=-1

Therefore, when a and B are identical, the values of the C of the modulo operation and the remainder operation are consistent, so the results are consistent. But when the symbols are inconsistent, the results are different.

In particular, the symbol of the result of the remainder operation is consistent with a, and the symbol of the result of the modulo operation is consistent with B.


In the C language, the% symbol represents the remainder operation, and in the Python script,% is the modulo. (usually b in modulo operations is not allowed to be negative, but in Python 2.5.1 It can be followed by a negative number, because the result of division in the Python language is rounding to 0, so the result is modulo.) )

The following table is a typical modulo or remainder value.

A
B
C Language: a%b (remainder)
Python shell:a%b (modulo)
-3 -5 -3 -3
-3 4 -3 1
-3 2 -1 1
-1 6 -1 5
-4 -3 -1 -1
2 4 2 2
5 3 2 2
4 -7 4 -3
4 -3 1 -2
-6 -5 -1 -1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.