How does modulo work with negative numbers?

QuestionsQuestions8 SkillsProPython Control StructuresSep, 23 2025
0238

The behavior of the modulo operator with negative numbers can vary depending on the programming language, but in many languages, including Python and Java, the result of the modulo operation takes the sign of the divisor (the second operand).

General Rule:

  • The result of a % b will have the same sign as b.

Examples:

  1. Positive Divisor:

    print(-10 % 3)  # Output: 2
    • Here, -10 divided by 3 gives a quotient of -4 and a remainder of 2 (since -10 = 3 * -4 + 2).
  2. Negative Divisor:

    print(10 % -3)  # Output: -2
    • In this case, 10 divided by -3 gives a quotient of -4 and a remainder of -2 (since 10 = -3 * -4 - 2).
  3. Both Negative:

    print(-10 % -3)  # Output: -1
    • Here, -10 divided by -3 gives a quotient of 3 and a remainder of -1 (since -10 = -3 * 3 - 1).

Summary:

  • The result of the modulo operation with negative numbers can be counterintuitive, so it's important to remember that the sign of the result is determined by the divisor.

If you have further questions or need examples in a specific programming language, let me know!

0 Comments

no data
Be the first to share your comment!