Find the modular multiplicative inverse of the given number with some mod.
Example:
Input: n = 3 , m = 26 Output: 9
Approach
Java
public class ModularMultiplicativeInverse {// declare variable to hold the variablestatic int x = 0, y = 0, d = 0;public static void main(String[] args) {int a = 3, m = 26;gcd(a, m);if (d != 1) {System.out.println("No modular inverse!");} else {x = (x % m + m) % m;System.out.println(x);}}// method to return GCD and find the// coefficient x any y// of the equation a*x+b*y=gcd(a,b)private static void gcd(int a, int b) {// base caseif (b == 0) {// set x=1x = 1;// set y=0y = 0;d = a;} else {// call GCD againgcd(b, a % b);// hold x value in tmpint tmp = x;// assign y into xx = y;// calculate by againy = tmp - a / b * y;}}}
C++
#include <bits/stdc++.h>using namespace std;//functoon to return GCD and find the//coefficient x any y//of the equation a*x+b*y=gcd(a,b)int gcd(int a,int b,int &x,int &y){//base caseif(b==0){//set x=1x=1;//set y=0y=0;return a;}//intermediate variablesint x1,y1;//now call the gcd functionint d=gcd(b,a%b,x1,y1);//formaula for x as x= y1x=y1;//formula for y as x1-y1*(a/b)y=x1-y1*(a/b);//return the gcdreturn d;}int main(){int a=3,m=26;int x,y;int d=gcd(a,m,x,y);if(d != 1) {cout << "No modular inverse!";}else {x = (x % m + m) % m;cout << x << endl;}return 0;}//Time Complexity: O(log(min(a,b)))
No comments:
Post a Comment