Java Integer Mod modularInverses(int p)

Here you can find the source of modularInverses(int p)

Description

This function returns the multiplicative inverses of the integers [0, 1, ..., p-1] in mod p arithmetic.

License

Open Source License

Parameter

Parameter Description
p a parameter

Return

an array containing the multiplicative inverses in the field Z/pZ

Declaration

public static int[] modularInverses(int p) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from   ww w .  j a va  2 s .  c o m
     * This function returns the multiplicative inverses of the integers
     * [0, 1, ..., p-1] in mod p arithmetic. Note that the 0-th index is 
     * simply set to 0 for convenience so that the inverse of n is in the n-th
     * component of the returned array.
     * 
     * TODO:
     * This is a somewhat inefficient way to compute the inverses, however it works
     * fine for small p.
     * 
     * @param p
     * @return an array containing the multiplicative inverses in the field Z/pZ
     */
    public static int[] modularInverses(int p) {
        int[] inverses = new int[p];
        for (int i = 1; i < p; i++) {
            int inverse = 0;
            for (int j = 1; j < p; j++) {
                if (((j * i) % p) == 1) {
                    inverse = j;
                    break;
                }
            }

            if (inverse == 0) {
                throw new IllegalArgumentException(p + " is not a prime.");
            }

            inverses[i] = inverse;
        }

        return inverses;
    }
}

Related

  1. modInverse(int n, int mod)
  2. modMultiply(long a, long b, int m)
  3. modPos(int divisor, int dividend)
  4. modSubtract(long a, long b, int m)
  5. modularExp(long base, long exp, int modulus)
  6. modularInvert(int num, int modulus)
  7. modulateCircularIndex(int index, int seqLength)
  8. modulo(int a, int b)
  9. modulo(int a, int b)