The Modulus Operator

We will learn about the modulus operator. The modulus operator (mod or %) finds the remainder of two numbers. 6 mod 4 = 2, because 6 divides into 4 once with a remainder of 2. It’s a bit like maths on a 12 hour clock: at 11 o’clock, if you add 2 hours, you get 1 o’clock, because 11 + 2 mod 12 = 1.

Watch the video and then answer the questions below.

Ten-minute video

You can also view this video on YouTube


Modulus in Java

In Java, you can find the modulus of two numbers, or the remainder of two numbers, by using the percent-sign (%). For example:


Modulus in Python

In Python, you can find the modulus of two numbers, or the remainder of two numbers, by using the percent-sign (%). For example:


Questions

1. Check your understanding

Modulus

Give an answer for each of the following, without using Java:

Check Answers

Congruance

Check the boxes for those values that are congruant modulo 43

Check Answers

2. Allocating players

Imagine you are writing code to allocate players in an online team-based multiplayer game like DOTA 2 or League of Legends. The game is played in games of 5v5 players. In our game, any unalocated players must wait in a lobby for more players to log on.

  1. Write a function in Java that takes the total number of players and returns the number of games.
  2. Write a function in Java that takes the total number of players and returns the number of players waiting in the lobby
  3. (Optional - extra programming challenge) Write a function that takes an array of players and assigns them each a number being the game to add them to, such that each game has exactly 10 players. Any unalocated players have a group number of None or -1.

Summary

In this section we learned about the modulus operator and how to use it in Java.

  • You should know what the modulus operator is and how to use it to find the modulus or remainder in Java.

Once you’ve completed the questions, you can move on to the next section on using modular arithmatic for cyphers.