### Calculating the GCD of Two Numbers

You can also use the modulo operator to quickly calculate the greatest common divisor (GCD) of two numbers. The trick is to keep calculating the modulo of the numbers and reassigning them until they divide completely.

We keep calculating $a%$b if $b does not completely divide $a. After each calculation, $b is assigned to $a, and the modulo we calculated earlier is assigned to $b. The value of $b when the modulo becomes 0 is our GCD.

### Calculating Modulus With Modular Exponentiation

Modular exponentation is used in many fields in computer science like cryptography. It relies on a property of modulus where:

We can create a function based on the above property to calcuate the remainder when dividing x y by m.

Calculating the modulo by first evaluating the exponent 44 123 would have given us a 203-digit number. It would be much bigger if the exponent is over 1,000. In such cases, using the above function will give us the modulo much more quickly.

The function simply returns 0 if the divisor is 1. Otherwise, it runs a for loop for \$exponent number of iterations and calculates the modulus at each point. The end result is simply the remainder that we would have gotten by calculating the value of exponential expression and taking the modulo of the result.

## Final Thoughts

As you saw in this tutorial, the modulo operator, though easy to use, has a lot of applications. We began this tutorial by looking at the modulo of both positive and negative numbers, as well as floats. After that, we covered some common scenarios where we would use modulo.

If you have any questions related to this tutorial, please let me know in the comments. Do you have any other uses of modulo in mind? Please share them with fellow readers by posting them below.

## Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

In this course, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.