SoFunction
Updated on 2025-03-02

(negative number) divisor and modulus operation method in python

python (negative number) divisor and modulus operation

Introduction

  • %:Take the modal symbol (in other languages, take the remainder symbol)
  • // :Divide the symbol, round down, and do not round

Mathematical description:

  • If there are integers n and m, where 0 <= m < b, soa = n * b + m,Som=a % b = a - n * b ,n = a // b.

The difference between taking remainder and taking mold

  • Remaining operation: discard the decimal places in the 0 direction during calculation (Follow the following as much as possible to make the Shangda University
  • Module operation: discard decimal places in the direction of negative infinity during calculation (Follow the following as much as possible to make the business small)

The positive number is the same as the modulus, so there is a difference between the negative number is the difference between the modulus

Give an example

Starting directly from the example, divide the positive number into the remainder and the negative number into the remainder and the negative number into the remainder and the

1. Take the remainder and get the mold

The positive number is equal to the remainder and the modulus:

5 / 3 = 1.67
5 mod 3 = 2  (Take a model)
5 rem 3 = 2  (Take the rest)

2. Negative number takes the remainder and get the mold

# Module: Discard decimal places in the negative infinite direction during calculation (round down)-5 mod 3 = 1  
# -5 / 3 Round down to -2, bringing the formula -5 - (3 * -2) = 15 mod -3 = -1
# 5 / -3 Round down to -2, bringing formula 5 - (-3 * -2) = -1-5 mod -3 = -2
# -5 / -3 Round down to 1, bringing the formula -5 - (-3 * 1) = 2

# Get the remainder: discard the decimal places in the direction of 0 (round them to 0)-5 rem 3 = -2
# -5 / 3 Round to 0 to -1, bringing the formula -5 - (3 * -1) = -25 rem -3 = 2
# 5 / -3 Round to 0 to -1, bringing formula 5 - (-3 * -1) = 2-5 rem -3 = -2
# -5 / -3 Towards0Round as1,Bring into formula -5 - (-3 * 1) = 2

Last note:

  • % is a modulo symbol in python
  • In other languages, it is the symbol of the rest! ! !

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.