Differences between a modulo operation and a remainder operation

Source: Internet
Author: User

In general, MOD and REM operations are confused, because mostProgramming Language'%'Symbol indicates the modulo operation or the remainder operation. Here, we would like to remind everyone to pay attention to the current environment'%'Specific meaning of the operator, because when a negative number exists, the two results are different.

For integer a and B, the modulo operation or remainder operation methods are as follows:

1. Calculate the integer quotient: c = A/B;

2. calculation mode or remainder: r = a-c * B.

The modulo operation and the remainder operation are different in the first step:ModuloWhen the remainder operation obtains the value of C, it rounds to 0 (the fix () function );WhileRemainderWhen the modulo operation calculates the value of C, it rounds the floor () function to an infinitely small direction ).

Therefore, when the symbols A and B are the same, the result is the same because the modulo operation and the result of the remainder operation are the same. But when the symbols are inconsistent, the results are different.

Specifically, the result of the modulo operation is the same as that of B, and the result of the remainder operation is the same as that of..

In C, the % symbol represents the remainder operation. In a Python script, % Represents the modulo. (In the modulo operation, B is not allowed to be a negative number, but in Python 2.5.1, it can be followed by a negative number after %, because in Python, the division result is rounded to 0, therefore, the calculation result is a modulo !)

The following table lists some typical modulo or remainder values.

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.