Modulo Operator

The modulo operator (%) computes the remainder after dividing one number by another. It has uses across mathematics, programming, and encryption.

For two numbers a and b:

a % b = remainder when a is divided by b

Some examples:

  • 7 % 3 = 1
  • 5 % 2 = 1
  • 10 % 7 = 3

The modulo operator appears in most programming languages:

Java example:

1
int remainder = 9 % 2; // 1

C++ example:

1
int remainder = 11 % 7; // 4 

Python example:

1
remainder = 12 % 5 # 2

Key properties:

  • Result has same sign as dividend
  • Magnitude is less than divisor
  • Allows creating cyclic sequences

The modulo operator is essential for arithmetic with integers and numerous algorithms. It provides the basis of modular arithmetic systems.

The modulo operator, often denoted by %, returns the remainder of the division of one number by another. For example, (7 \mod 3 = 1) because when 7 is divided by 3, the quotient is 2 and the remainder is 1. The modulo operator is commonly used in various programming and mathematical tasks such as hashing, circular arrays, and periodic functions.

Code in Java

Here’s how you can use the modulo operator in Java.

1
2
3
4
5
6
7
8
public class ModuloExample {
    public static void main(String[] args) {
        int a = 7;
        int b = 3;
        int result = a % b;
        System.out.println("7 % 3 = " + result);
    }
}

Code in C++

Here’s a C++ example.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <iostream>
using namespace std;

int main() {
    int a = 7;
    int b = 3;
    int result = a % b;
    cout << "7 % 3 = " << result << endl;
    return 0;
}

Code in Python

Python code example.

1
2
3
4
a = 7
b = 3
result = a % b
print(f"7 % 3 = {result}")

The output for all these code snippets will be 7 % 3 = 1. As you can see, the modulo operator is used similarly in Java, C++, and Python.