Search code examples
matlabfunctioninversemodulo

Modular Multiplicative Inverse function in matlab


I have problem for calculate modular multiplicative inverse. example I have integer A = 151 and M = 541. 151 mod 541. inverse mod 151 to 541 is 43 how to calculate modular multiplicative inverse in matlab ?


Solution

  • This can be done using gcd and mod functions as follows:

    A = 151;   M = 541;
    
    [G, C, ~] = gcd(A,M);
    if G==1  % The inverse of a(mod b) exists only if gcd(a,b)=1
        ModMultInv = mod(C,M)
    else disp('Modular multiplicative inverse does not exist for these values')
    end
    

    Output:-

    ModMultInv =
        43