# List of invertible congruence classes

I am attempting to create a list of the invertible congruence classes $$\bmod 120$$.

The code I have is Table[If[{ModularInverse[i, 120]} = {}, 120, ModularInverse[i, 120]], {i, 0, 119}]

If the modular inverse does not exist, it should return $$120$$. If it does exist, it should return the integer that corresponds to the inverse congruence class.

The code is not working how I expected it to. If the modular inverse does not exists, it gives me a list with the unevaluated code, for example, ModularInverse[0, 120].

• Not the only problem, but one thing to note: Equality is tested with a double-equals ==. – Michael E2 Feb 26 at 2:50

## 1 Answer

Note what happens when i does not have an inverse:

ModularInverse[2, 120]


ModularInverse::ninv: 2 is not invertible modulo 120.

(*  Out[]=  ModularInverse[2, 120]  *)


The output is the same as the input (it returns "unevaluated" in Mma jargon). You can use FreeQ to see if the inverse returned unevaluated:

Table[With[{inv = Quiet@ModularInverse[i, 120]},
If[FreeQ[inv, ModularInverse], inv, 120]], {i, 0, 119}]

• You can also use Check[]: Table[Quiet[Check[ModularInverse[i, 120], 120, ModularInverse::ninv]], {i, 0, 119}]. – J. M. is away Feb 26 at 8:10