How to perform modular arithmetic in R

Today, we will see how to compute a modulo, how to perform modular arithmetic and why it can be useful for some bioinformatics tasks in R. For example, it is used in one of the Rosalind problems.

What is a modulo

A modulus is what remains when we divide an integer by another integer (called the modulo). For example, 12 modulo 5 gives 2 as a remainder (12 = 5 * 2 + 2). In the R programming language, the modulo operator is defined by the %% symbol.

Let’s take the modulo 11 of four integers a, b, c and d:

a = 39
b = 50
c = 84
d = 7
n = 11

We can say that a and b are congruent because they give the same remainder (39 = 11 * 3 + 6 and 50 = 11 * 4 + 6):

> a %% n
[1] 6
> b %% n
[1] 6

In this example, c and d are also congruent (84 = 11 * 7 + 7 and 7 = 11 * 0 + 7):

> c %% n
[1] 7
> d %% n
[1] 7

Modular arithmetic

Now we can perform some arithmetic on the modulos: addition, subtraction and multiplication. Let’s keep the five integers a, b, c, d and n that have been defined in the previous section.

1. Modular addition

> (a + c) %% n
[1] 2
> (b + d) %% n
[1] 2

2. Modular subtraction

> (a - c) %% n
[1] 10
> (b - d) %% n
[1] 10

3. Modular multiplication

> (a * c) %% n
[1] 9
> (b * d) %% n
[1] 9

Application

An example of application is the use of modular multiplication to avoid the computational problems coming from the manipulation of very large numbers in R.

For instance, if we want to take the modulus 1,000,000 of 7^50, it throws an error:

number = 7^50
> print(number)
[1] 1.798465e+42
> print(number %% 1000000)
[1] 0
Warning message:
In print(number%%1e+06) : probable complete loss of accuracy in modulus

However, if we compute the modulus 1,000,000 at each step, we don’t get any error:

number = 1

for (i in seq(1, 50)){
  number = number * 7

  if (number %% 1000000 != 0){
    number = number %% 1000000
  }
}
> print(number)
[1] 251249

Conclusion

In conclusion, this example of modular arithmetic shows how to avoid the imprecision of very large numbers in R.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply