Skip to content
๐Ÿ”ข Euclidean Division vs Floor Division in Python

๐Ÿ”ข Euclidean Division vs Floor Division in Python

  • Floor Division (//): Rounds the result of division toward negative infinity.
  • Euclidean Division: Ensures the remainder is always non-negative, adjusting the quotient if necessary.

๐Ÿง  Python Behavior

  • Pythonโ€™s // operator performs floor division.
  • Pythonโ€™s % operator adjusts the remainder to be non-negative when the divisor is positive, making it behave like Euclidean division in many cases.

โœ… Example with Positive Divisor

  • -7 // 3 โ†’ -3
  • -7 % 3 โ†’ 2
  • -7 = 3 ร— (-3) + 2 โ†’ Matches Euclidean division

โš ๏ธ Example with Negative Divisor

  • -7 // -3 โ†’ 2
  • -7 % -3 โ†’ -1
  • -7 = (-3) ร— 2 + (-1) โ†’ Not Euclidean (remainder is negative)

๐Ÿงฎ Euclidean Quotient Function

def euclidean_quotient(a, b):
    q = a // b
    r = a % b
    return q if r >= 0 else q + 1

โœ… Summary Table

CaseFloor QuotientEuclidean Quotient
-7 // 3-3-3
-7 // -323

๐Ÿ’ก Final Insight

  • Use // and % together for Euclidean-like behavior when the divisor is positive.
  • For consistent Euclidean division regardless of sign, use a custom function like euclidean_quotient(a, b).
  • Pythonโ€™s // performs floor division, which may differ from Euclidean division when negative divisors are involved.
  • Understanding the distinction helps avoid subtle bugs in modular arithmetic, cryptography, and number theory applications.
Last updated on