División Modular

Dados tres números positivos a, b y m. Calcule a/b bajo módulo m. La tarea es básicamente encontrar un número c tal que (b * c) % m = a % m.
Ejemplos: 

Input  : a  = 8, b = 4, m = 5
Output : 2

Input  : a  = 8, b = 3, m = 5
Output : 1
Note that (1*3)%5 is same as 8%5

Input  : a  = 11, b = 4, m = 5
Output : 4
Note that (4*4)%5 is same as 11%5

Los siguientes artículos son requisitos previos para esto. 
Multiplicativo modular inverso  
Algoritmos euclidianos extendidos  
¿Podemos hacer siempre divisiones modulares?  
La respuesta es no». En primer lugar, al igual que la aritmética ordinaria, la división por 0 no está definida. Por ejemplo, 4/0 no está permitido. En la aritmética modular, no solo no se permite 4/0, sino que tampoco se permite 4/12 bajo el módulo 6. La razón es que 12 es congruente con 0 cuando el módulo es 6. ¿
Cuándo se define la división modular?  
La división modular se define cuando existe el inverso modular del divisor. El inverso de un entero ‘x’ es otro entero ‘y’ tal que (x*y) % m = 1 donde m es el módulo. 
¿Cuándo existe el inverso? Como se discutió aquí, el inverso de un número ‘a’ existe bajo el módulo ‘m’ si ‘a’ y ‘m’ son coprimos, es decir, el MCD de ellos es 1. ¿Cómo encontrar la división modular
? 

The task is to compute a/b under modulo m.
1) First check if inverse of b under modulo m exists or not. 
    a) If inverse doesn't exists (GCD of b and m is not 1), 
          print "Division not defined"
    b) Else return  "(inverse * a) % m" 

C++

// C++ program to do modular division
#include<iostream>
using namespace std;
 
// C++ function for extended Euclidean Algorithm
int gcdExtended(int a, int b, int *x, int *y);
 
// Function to find modulo inverse of b. It returns
// -1 when inverse doesn't
int modInverse(int b, int m)
{
    int x, y; // used in extended GCD algorithm
    int g = gcdExtended(b, m, &x, &y);
 
    // Return -1 if b and m are not co-prime
    if (g != 1)
        return -1;
 
    // m is added to handle negative x
    return (x%m + m) % m;
}
 
// Function to compute a/b under modulo m
void modDivide(int a, int b, int m)
{
    a = a % m;
    int inv = modInverse(b, m);
    if (inv == -1)
       cout << "Division not defined";
    else
       cout << "Result of division is " << (inv * a) % m;
}
 
// C function for extended Euclidean Algorithm (used to
// find modular inverse.
int gcdExtended(int a, int b, int *x, int *y)
{
    // Base Case
    if (a == 0)
    {
        *x = 0, *y = 1;
        return b;
    }
 
    int x1, y1; // To store results of recursive call
    int gcd = gcdExtended(b%a, a, &x1, &y1);
 
    // Update x and y using results of recursive
    // call
    *x = y1 - (b/a) * x1;
    *y = x1;
 
    return gcd;
}
 
// Driver Program
int main()
{
    int  a  = 8, b = 3, m = 5;
    modDivide(a, b, m);
    return 0;
}
 
//this code is contributed by khushboogoyal499

C

// C program to do modular division
#include <stdio.h>
 
// C function for extended Euclidean Algorithm
int gcdExtended(int a, int b, int *x, int *y);
 
// Function to find modulo inverse of b. It returns
// -1 when inverse doesn't
int modInverse(int b, int m)
{
    int x, y; // used in extended GCD algorithm
    int g = gcdExtended(b, m, &x, &y);
 
    // Return -1 if b and m are not co-prime
    if (g != 1)
        return -1;
 
    // m is added to handle negative x
    return (x%m + m) % m;
}
 
// Function to compute a/b under modulo m
void modDivide(int a, int b, int m)
{
    a = a % m;
    int inv = modInverse(b, m);
    if (inv == -1)
     printf ("Division not defined");
    else
    {
      int c = (inv * a) % m ;
       printf ("Result of division is %d", c) ;
    }
}
 
// C function for extended Euclidean Algorithm (used to
// find modular inverse.
int gcdExtended(int a, int b, int *x, int *y)
{
    // Base Case
    if (a == 0)
    {
        *x = 0, *y = 1;
        return b;
    }
 
    int x1, y1; // To store results of recursive call
    int gcd = gcdExtended(b%a, a, &x1, &y1);
 
    // Update x and y using results of recursive
    // call
    *x = y1 - (b/a) * x1;
    *y = x1;
 
    return gcd;
}
 
// Driver Program
int main()
{
    int  a  = 8, b = 3, m = 5;
    modDivide(a, b, m);
    return 0;
}

Java

// java program to do modular division
 
import java.io.*;
import java.lang.Math;
 
public class GFG {
 
    static int gcd(int a,int b){
        if (b == 0){
            return a;
        }        
        return gcd(b, a % b);
    }
     
    // Function to find modulo inverse of b. It returns
    // -1 when inverse doesn't
    // modInverse works for prime m
    static int modInverse(int b,int m){
        int g = gcd(b, m) ;
        if (g != 1)
            return -1;
        else
        {
            //If b and m are relatively prime,
            //then modulo inverse is b^(m-2) mode m
            return (int)Math.pow(b, m - 2) % m;
        }
    }
     
    // Function to compute a/b under modulo m
    static void modDivide(int a,int b,int m){
        a = a % m;
        int inv = modInverse(b,m);
        if(inv == -1){
            System.out.println("Division not defined");
        }  
        else{
             System.out.println("Result of Division is " + ((inv*a) % m));
        }
    } 
     
    // Driver Program
    public static void main(String[] args) {
        int a = 8;
        int b = 3;
        int m = 5;
        modDivide(a, b, m);
    }
}
 
// The code is contributed by Gautam goel (gautamgoel962)

Python3

# Python3 program to do modular division
import math
 
# Function to find modulo inverse of b. It returns
# -1 when inverse doesn't
# modInverse works for prime m
def modInverse(b,m):
    g = math.gcd(b, m)
    if (g != 1):
        # print("Inverse doesn't exist")
        return -1
    else:
        # If b and m are relatively prime,
        # then modulo inverse is b^(m-2) mode m
        return pow(b, m - 2, m)
 
 
# Function to compute a/b under modulo m
def modDivide(a,b,m):
    a = a % m
    inv = modInverse(b,m)
    if(inv == -1):
        print("Division not defined")
    else:
        print("Result of Division is ",(inv*a) % m)
 
# Driver Program
a = 8
b = 3
m = 5
modDivide(a, b, m)
 
# This code is Contributed by HarendraSingh22

C#

using System;
 
// C# program to do modular division
class GFG {
 
  // Recursive Function  to find
  // GCD of two numbers
  static int gcd(int a,int b){
    if (b == 0){
      return a;
    }        
    return gcd(b, a % b);
  }
 
  // Function to find modulo inverse of b. It returns
  // -1 when inverse doesn't
  // modInverse works for prime m
  static int modInverse(int b,int m){
    int g = gcd(b, m) ;
    if (g != 1){
      return -1;
    }       
    else
    {
 
      //If b and m are relatively prime,
      //then modulo inverse is b^(m-2) mode m
      return (int)Math.Pow(b, m - 2) % m;
    }
  }
 
  // Function to compute a/b under modulo m
  static void modDivide(int a,int b,int m){
    a = a % m;
    int inv = modInverse(b,m);
    if(inv == -1){
      Console.WriteLine("Division not defined");
    }  
    else{
      Console.WriteLine("Result of Division is " + ((inv*a) % m));
    }
  } 
 
  // Driver Code
  static void Main() {
    int a = 8;
    int b = 3;
    int m = 5;
    modDivide(a, b, m);
  }
}
 
// The code is contributed by Gautam goel (gautamgoel962)

Javascript

<script>
// JS program to do modular division
function gcd(a, b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
// Function to find modulo inverse of b. It returns
// -1 when inverse doesn't
// modInverse works for prime m
function modInverse(b,m)
{
    g = gcd(b, m) ;
    if (g != 1)
        return -1;
    else
    {
        //If b and m are relatively prime,
        //then modulo inverse is b^(m-2) mode m
        return Math.pow(b, m - 2, m);
    }
}
 
// Function to compute a/b under modulo m
function modDivide(a,b,m)
{
    a = a % m;
    inv = modInverse(b,m);
    if(inv == -1)
        document.write("Division not defined");
    else
        document.write("Result of Division is ",(inv*a) % m);
}
 
// Driver Program
a = 8;
b = 3;
m = 5;
modDivide(a, b, m);
 
// This code is Contributed by phasing17
</script>

PHP

<?php
// PHP program to do modular division
 
// Function to find modulo inverse of b.
// It returns -1 when inverse doesn't
function modInverse($b, $m)
{
    $x = 0;
    $y = 0; // used in extended GCD algorithm
    $g = gcdExtended($b, $m, $x, $y);
 
    // Return -1 if b and m are not co-prime
    if ($g != 1)
        return -1;
 
    // m is added to handle negative x
    return ($x % $m + $m) % $m;
}
 
// Function to compute a/b under modulo m
function modDivide($a, $b, $m)
{
    $a = $a % $m;
    $inv = modInverse($b, $m);
    if ($inv == -1)
        echo "Division not defined";
    else
        echo "Result of division is " .
                      ($inv * $a) % $m;
}
 
// function for extended Euclidean Algorithm
// (used to find modular inverse.
function gcdExtended($a, $b, &$x, &$y)
{
    // Base Case
    if ($a == 0)
    {
        $x = 0;
        $y = 1;
        return $b;
    }
 
    $x1 = 0;
    $y1 = 0; // To store results of recursive call
    $gcd = gcdExtended($b % $a, $a, $x1, $y1);
 
    // Update x and y using results of
    // recursive call
    $x = $y1 - (int)($b / $a) * $x1;
    $y = $x1;
 
    return $gcd;
}
 
// Driver Code
$a = 8;
$b = 3;
$m = 5;
modDivide($a, $b, $m);
 
// This code is contributed by mits
?>

Producción: 

Result of division is 1

La división modular es diferente de la suma, la resta y la multiplicación.  
Una diferencia es que la división no siempre existe (como se discutió anteriormente). Lo siguiente es otra diferencia. 
 

Below equations are valid
(a * b) % m = ((a % m) * (b % m)) % m
(a + b) % m = ((a % m) + (b % m)) % m

// m is added to handle negative numbers
(a - b + m) % m = ((a % m) - (b % m) + m) % m 

But, 
(a / b) % m may NOT be same as ((a % m)/(b % m)) % m

For example, a = 10, b = 5, m = 5. 
   (a / b) % m is 2, but ((a % m) / (b % m)) % m 
                          is not defined.

Referencias:  
http://www.doc.ic.ac.uk/~mrh/330tutor/ch03.html
Este artículo es una contribución de Dheeraj Gupta . Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *