Open In App

Modulo Operations in Programming With Negative Results

In programming, the modulo operation gives the remainder or signed remainder of a division, after one integer is divided by another integer. It is one of the most used operators in programming. This article discusses when and why the modulo operation yields a negative result.

Examples:



Hence, it’s evident that the same expression of -3 % 2 gives different results in different programming languages. This result is more related to mathematics rather than programming. The mathematics mentioned here will help in understanding the questions a little more easily. 
To understand why this happens, a little knowledge about Euclidean Division and a few points related to Modular Arithmetic is needed.

Euclidean Division: In arithmetic, Euclidean division or division with the remainder is the process of dividing one integer (the dividend) by another (the divisor), in such a way that it produces a quotient and a remainder smaller than the divisor.



Given two integers a and b ( where b ≠ 0 ), there exists unique integers q and r such that:

a = bq + r ( 0 ≤ r < |b|
where, |b| denotes the absolute value of b.

In the above equation, each of the four integers has its own name i.e.,

For Example:

Explanations of the above examples:

Modular Arithmetic: In mathematics, modular arithmetic is a system of arithmetic for integers, where numbers “wrap around” when reaching a certain value, called the modulus.

Congruence: Given any integer N, called a modulus, two integers a and b are said to be congruent modulo N if they produce the same remainder when divided by N i.e.,

a = pN + r and b = qN + r, where 0 ≤ r < |N| is the common remainder.

Congruence modulo N is denoted as a ≡ b (mod N) 
where the parentheses means that (mod N) applies to the entire equation, not just to the right-hand side ( here b).

Examples:

Analyzing the first example. -5 = 7 × -1 + 2 and 2 = 7 × 0 + 2. Both -5 and 2 leave the same remainder 2 when divided by 7. Hence, they are congruent to each other. 
Similarly, -14 = 11 × -2 + 8 and 19 = 11 × 1 + 8. Both -14 and 19 leave the same remainder 8 when divided by 11. Hence, they are congruent to each other. 

Congruence Classes: Suppose a mod N leaves a remainder r when divided by N satisfying the condition 0 ≤ r < |N|.  The set of all the integers congruent to a mod N is called the congruence class of the integer a mod N. For Example:

Select any integer from the congruence class of the integer a mod N as a representative of that class. In mathematics, the least positive residue, the smallest non-negative integer that belongs to that class is chosen as the representative. For Example: 

The Least positive residue is chosen because it is the remainder produced after the Euclidean division.

Representative is chosen by Programming languages:

Implementations of % in Programming languages: Many programming languages like C, C++, Java, JavaScript use an implementation similar to the one given below. The remainder is returned according to the equation

r = a – N*trunc(a/N)

Below is the implementation of the above explanation:




// C++14 program to illustrate modulo
// operations using the above equation
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate and
// return the remainder of a % n
int truncMod(int a, int n)
{
     
    // (a / n) implicitly gives
    // the truncated result
    int q = a / n;
 
    return a - n * q;
}
 
// Driver Code
int main()
{
    int a, b;
 
    // Modulo of two positive numbers
    a = 9;
    b = 4;
    cout << a << " % "
         << b << " = "
         << truncMod(a, b) << endl;
 
    // Modulo of a negative number
    // by a positive number
    a = -9;
    b = 4;
    cout << a << " % "
         << b << " = "
         << truncMod(a, b) << endl;
 
    // Modulo of a positive number
    // by a negative number
    a = 9;
    b = -4;
    cout << a << " % "
         << b << " = "
         << truncMod(a, b) << endl;
 
    // Modulo of two negative numbers
    a = -9;
    b = -4;
    cout << a << " % "
         << b << " = "
         << truncMod(a, b) << endl;
}
 
// This code is contributed by mohit kumar 29




// Java program to illustrate modulo
// operations using the above equation
class GFG {
 
    // Function to calculate and
    // return the remainder of a % n
    static int truncMod(int a, int n)
    {
        // (a / n) implicitly gives
        // the truncated result
        int q = a / n;
 
        return a - n * q;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int a, b;
 
        // Modulo of two positive numbers
        a = 9;
        b = 4;
        System.out.println(a + " % " + b + " = "
                           + truncMod(a, b));
 
        // Modulo of a negative number
        // by a positive number
        a = -9;
        b = 4;
        System.out.println(a + " % " + b + " = "
                           + truncMod(a, b));
 
        // Modulo of a positive number
        // by a negative number
        a = 9;
        b = -4;
        System.out.println(a + " % " + b + " = "
                           + truncMod(a, b));
 
        // Modulo of two negative numbers
        a = -9;
        b = -4;
        System.out.println(a + " % " + b + " = "
                           + truncMod(a, b));
    }
}




# Python3 program to illustrate modulo
# operations using the above equation
 
# Function to calculate and
# return the remainder of a % n
def truncMod(a, n):
   
    # (a / n) implicitly gives
    # the truncated result
    q = a // n
    return a - n * q
 
# Driver Code
if __name__ == '__main__':
   
    # Modulo of two positive numbers
    a = 9
    b = 4
    print(a,"%",b,"=",truncMod(a, b))
 
    # Modulo of a negative number
    # by a positive number
    a = -9
    b = 4
    print(a,"%",b,"=",truncMod(a, b))
 
    # Modulo of a positive number
    # by a negative number
    a = 9
    b = -4
    print(a,"%",b,"=",truncMod(a, b))
 
    # Modulo of two negative numbers
    a = -9
    b = -4
    print(a,"%",b,"=",truncMod(a, b))
     
    # This code is contributed by SURENDRA_GANGWAR.




// C# program for the above approach
using System;
public class GFG
{
 
  // Function to calculate and
  // return the remainder of a % n
  static int truncMod(int a, int n)
  {
     
    // (a / n) implicitly gives
    // the truncated result
    int q = a / n;
    return a - n * q;
  }
 
  // Driver Code
  static public void Main()
  {
 
    int a, b;
 
    // Modulo of two positive numbers
    a = 9;
    b = 4;
    Console.WriteLine(a + " % " + b + " = "
                      + truncMod(a, b));
 
    // Modulo of a negative number
    // by a positive number
    a = -9;
    b = 4;
    Console.WriteLine(a + " % " + b + " = "
                      + truncMod(a, b));
 
    // Modulo of a positive number
    // by a negative number
    a = 9;
    b = -4;
    Console.WriteLine(a + " % " + b + " = "
                      + truncMod(a, b));
 
    // Modulo of two negative numbers
    a = -9;
    b = -4;
    Console.WriteLine(a + " % " + b + " = "
                      + truncMod(a, b));
  }
}
 
// This code is contributed by snjoy_62.




<script>
 
// JavaScript program to illustrate modulo
// operations using the above equation
 
// Function to calculate and
    // return the remainder of a % n
function truncMod(a,n)
{
    // (a / n) implicitly gives
        // the truncated result
        let q = Math.round(a / n);
         
        return a - (n * q);
}
 
let a, b;
// Modulo of two positive numbers
a = 9;
b = 4;
document.write(a + " % " + b + " = "
                   + truncMod(a, b)+"<br>");
 
// Modulo of a negative number
// by a positive number
a = -9;
b = 4;
document.write(a + " % " + b + " = "
                   + truncMod(a, b)+"<br>");
 
// Modulo of a positive number
// by a negative number
a = 9;
b = -4;
document.write(a + " % " + b + " = "
                   + truncMod(a, b)+"<br>");
 
// Modulo of two negative numbers
a = -9;
b = -4;
document.write(a + " % " + b + " = "
                   + truncMod(a, b)+"<br>");
 
 
// This code is contributed by patel2127
 
</script>

Output: 
9 % 4 = 1
-9 % 4 = -1
9 % -4 = 1
-9 % -4 = -1

 

Note: Other programming languages with above implementation generates similar outcome. Notice something interesting, when the dividend is negative, the answer produced will also be negative, and it will be the greatest negative member of that congruence class. When the dividend is positive, the answer produced will also be positive and the least positive member of that congruence class.

Many programming languages like Python, Ruby, and Perl use an implementation similar to the one given below. The remainder is returned according to the equation

r = a – N × floor(a/b)

Below is the implementation of the above explanation:




// C++ program to illustrate modulo
// operations using the above equation
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate and
// return the remainder of a % n
int floorMod(int a, int n)
{
     
    // Type casting is necessary
    // as (int) / (int) will give
    // int result, i.e. -3 / 2
    // will give -1 and not -1.5
    int q = (int)floor((double)a / n);
 
    // Return the resultant remainder
    return a - n * q;
}
 
// Driver Code
int main()
{
    int a, b;
 
    // Modulo of two positive numbers
    a = 9;
    b = 4;
    cout << a << " % " << b
         << " = " << floorMod(a, b) << "\n";
 
    // Modulo of a negative number
    // by a positive number
    a = -9;
    b = 4;
    cout << a << " % " << b
         << " = " << floorMod(a, b) << "\n";
 
    // Modulo of a positive number
    // by a negative number
    a = 9;
    b = -4;
    cout << a << " % " << b
         << " = " << floorMod(a, b) << "\n";
 
    // Modulo of two negative numbers
    a = -9;
    b = -4;
    cout << a << " % " << b
         << " = " << floorMod(a, b) << "\n";
 
    return 0;
}
 
// This code is contributed by Kingash




// Java program to illustrate modulo
// operations using the above equation
public class GFG {
 
    // Function to calculate and
    // return the remainder of a % n
    static int floorMod(int a, int n)
    {
        // Type casting is necessary
        // as (int) / (int) will give
        // int result, i.e. -3 / 2
        // will give -1 and not -1.5
        int q = (int)Math.floor((double)a / n);
 
        // Return the resultant remainder
        return a - n * q;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int a, b;
 
        // Modulo of two positive numbers
        a = 9;
        b = 4;
        System.out.println(a + " % " + b + " = "
                           + floorMod(a, b));
 
        // Modulo of a negative number
        // by a positive number
        a = -9;
        b = 4;
        System.out.println(a + " % " + b + " = "
                           + floorMod(a, b));
 
        // Modulo of a positive number
        // by a negative number
        a = 9;
        b = -4;
        System.out.println(a + " % " + b + " = "
                           + floorMod(a, b));
 
        // Modulo of two negative numbers
        a = -9;
        b = -4;
        System.out.println(a + " % " + b + " = "
                           + floorMod(a, b));
    }
}




# Python program to illustrate modulo
# operations using the above equation
 
# Function to calculate and return the remainder of a % n
def floor_mod(a,n):
    # Use the built-in modulo operator
    return a % n
 
# Driver Code
a = 9
b = 4
print(str(a) + " % " + str(b) + " = " + str(floor_mod(a, b)))
 
# Modulo of a negative number by a positive number
a = -9
b = 4
print(str(a) + " % " + str(b) + " = " + str(floor_mod(a, b)))
 
# Modulo of a positive number by a negative number
a = 9
b = -4
print(str(a) + " % " + str(b) + " = " + str(floor_mod(a, b)))
 
# Modulo of two negative numbers
a = -9
b = -4
print(str(a) + " % " + str(b) + " = " + str(floor_mod(a, b)))




// C# program to illustrate modulo
// operations using the above equation
using System;
 
class GFG{
     
// Function to calculate and
// return the remainder of a % n
static int floorMod(int a, int n)
{
     
    // Type casting is necessary
    // as (int) / (int) will give
    // int result, i.e. -3 / 2
    // will give -1 and not -1.5
    int q = (int)Math.Floor((double)a / n);
 
    // Return the resultant remainder
    return a - n * q;
}
 
// Driver code
static public void Main()
{
    int a, b;
 
    // Modulo of two positive numbers
    a = 9;
    b = 4;
   Console.WriteLine(a + " % " + b + " = " +
                     floorMod(a, b));
 
    // Modulo of a negative number
    // by a positive number
    a = -9;
    b = 4;
    Console.WriteLine(a + " % " + b + " = " +
                      floorMod(a, b));
 
    // Modulo of a positive number
    // by a negative number
    a = 9;
    b = -4;
    Console.WriteLine(a + " % " + b + " = " +
                      floorMod(a, b));
 
    // Modulo of two negative numbers
    a = -9;
    b = -4;
    Console.WriteLine(a + " % " + b + " = " +
                      floorMod(a, b));
}
}
 
// This code is contributed by offbeat




<script>
 
// JavaScript program to illustrate modulo
// operations using the above equation
 
 // Function to calculate and
    // return the remainder of a % n
function floorMod(a,n)
{
    // Type casting is necessary
        // as (int) / (int) will give
        // int result, i.e. -3 / 2
        // will give -1 and not -1.5
        let q = Math.floor(Math.floor(a / n));
  
        // Return the resultant remainder
        return a - n * q;
}
 
// Driver Code
let a, b;
  
// Modulo of two positive numbers
a = 9;
b = 4;
document.write(a + " % " + b + " = "
                   + floorMod(a, b)+"<br>");
 
// Modulo of a negative number
// by a positive number
a = -9;
b = 4;
document.write(a + " % " + b + " = "
                   + floorMod(a, b)+"<br>");
 
// Modulo of a positive number
// by a negative number
a = 9;
b = -4;
document.write(a + " % " + b + " = "
                   + floorMod(a, b)+"<br>");
 
// Modulo of two negative numbers
a = -9;
b = -4;
document.write(a + " % " + b + " = "
                   + floorMod(a, b)+"<br>");
 
 
// This code is contributed by unknown2108
 
</script>

Output: 
9 % 4 = 1
-9 % 4 = 3
9 % -4 = -3
-9 % -4 = -1

 

Note: Other programming languages having above implementation generates similar outcome. Now, when the divisor is negative, the answer produced will also be negative as well as the greatest negative member of that congruence class. When the divisor is positive, the answer produced will also be positive, and it will be the least positive member of that congruence class.

All languages are producing correct results. They are just choosing different representatives of that solution congruent class. In order to produce only the least positive residue of the congruent class as the answer irrespective of the implementation used.

Below is the implementation of the above approach:




// C++ program for the above idea
#include <bits/stdc++.h>
using namespace std;
 
// Driver Code
int main()
{
    int a, b, r;
 
    // Modulo of two positive numbers
    a = 9;
    b = 4;
    r = a % b > 0 ? a % b : abs(b) + a % b;
    cout << a << " % " << b << " = " << r << "\n";
 
    // Modulo of a negative number
    // by a positive number
    a = -9;
    b = 4;
    r = a % b > 0 ? a % b : abs(b) + a % b;
    cout << a << " % " << b << " = " << r << "\n";
 
    // Modulo of a positive number
    // by a negative number
    a = 9;
    b = -4;
    r = a % b > 0 ? a % b : abs(b) + a % b;
    cout << a << " % " << b << " = " << r << "\n";
 
    // Modulo of two negative numbers
    a = -9;
    b = -4;
    r = a % b > 0 ? a % b : abs(b) + a % b;
    cout << a << " % " << b << " = " << r << "\n";
 
    return 0;
}
 
// This code is contributed by Kingash




// Java program for the above idea
public class PositiveModulus {
    // Driver Code
    public static void main(String args[])
    {
        int a, b, r;
 
        // Modulo of two positive numbers
        a = 9;
        b = 4;
        r = a % b > 0 ? a % b : Math.abs(b) + a % b;
        System.out.println(a + " % " + b + " = " + r);
 
        // Modulo of a negative number
        // by a positive number
        a = -9;
        b = 4;
        r = a % b > 0 ? a % b : Math.abs(b) + a % b;
        System.out.println(a + " % "
                           + b + " = " + r);
 
        // Modulo of a positive number
        // by a negative number
        a = 9;
        b = -4;
        r = a % b > 0 ? a % b : Math.abs(b) + a % b;
        System.out.println(a + " % "
                           + b + " = " + r);
 
        // Modulo of two negative numbers
        a = -9;
        b = -4;
        r = a % b > 0 ? a % b : Math.abs(b) + a % b;
        System.out.println(a + " % "
                           + b + " = " + r);
    }
}




# Modulo of two positive numbers
a = 9
b = 4
 
# If the modulo is greater than 0, set r to the modulo
# Otherwise, set r to the absolute value of b plus the modulo
r = a % b if a % b > 0 else abs(b) + a % b
print(f"{a} % {b} = {r}")
 
# Modulo of a negative number by a positive number
a = -9
b = 4
 
# If the modulo is greater than 0, set r to the modulo
# Otherwise, set r to the absolute value of b plus the modulo
r = a % b if a % b > 0 else abs(b) + a % b
print(f"{a} % {b} = {r}")
 
# Modulo of a positive number by a negative number
a = 9
b = -4
 
# If the modulo is greater than 0, set r to the modulo
# Otherwise, set r to the absolute value of b plus the modulo
r = a % b if a % b > 0 else abs(b) + a % b
print(f"{a} % {b} = {r}")
 
# Modulo of two negative numbers
a = -9
b = -4
 
# If the modulo is greater than 0, set r to the modulo
# Otherwise, set r to the absolute value of b plus the modulo
r = a % b if a % b > 0 else abs(b) + a % b
print(f"{a} % {b} = {r}")
 
# This code is contributed by phasing17.




// C# program for the above idea
using System;
using System.Collections.Generic;
 
class GFG{
 
// Driver Code
public static void Main(string[] args)
{
    int a, b, r;
 
    // Modulo of two positive numbers
    a = 9;
    b = 4;
    r = a % b > 0 ? a % b : Math.Abs(b) + a % b;
    Console.WriteLine(a + " % " + b + " = " + r);
 
    // Modulo of a negative number
    // by a positive number
    a = -9;
    b = 4;
    r = a % b > 0 ? a % b : Math.Abs(b) + a % b;
    Console.WriteLine(a + " % " + b + " = " + r);
 
    // Modulo of a positive number
    // by a negative number
    a = 9;
    b = -4;
    r = a % b > 0 ? a % b : Math.Abs(b) + a % b;
    Console.WriteLine(a + " % " + b + " = " + r);
 
    // Modulo of two negative numbers
    a = -9;
    b = -4;
    r = a % b > 0 ? a % b : Math.Abs(b) + a % b;
    Console.WriteLine(a + " % " + b + " = " + r);
}
}
 
// This code is contributed by avijitmondal1998




<script>
 
let a, b, r;
  
// Modulo of two positive numbers
a = 9;
b = 4;
r = a % b > 0 ? a % b : Math.abs(b) + a % b;
document.write(a + " % " + b + " = " + r+"<br>");
 
// Modulo of a negative number
// by a positive number
a = -9;
b = 4;
r = a % b > 0 ? a % b : Math.abs(b) + a % b;
document.write(a + " % "
                   + b + " = " + r+"<br>");
 
// Modulo of a positive number
// by a negative number
a = 9;
b = -4;
r = a % b > 0 ? a % b : Math.abs(b) + a % b;
document.write(a + " % "
                   + b + " = " + r+"<br>");
 
// Modulo of two negative numbers
a = -9;
b = -4;
r = a % b > 0 ? a % b : Math.abs(b) + a % b;
document.write(a + " % "
                   + b + " = " + r+"<br>");
 
 
 
 
// This code is contributed by unknown2108
</script>

Output: 
9 % 4 = 1
-9 % 4 = 3
9 % -4 = 1
-9 % -4 = 3

 


Article Tags :