Skip to content

Instantly share code, notes, and snippets.

@mcichecki
Created June 23, 2018 11:03

Revisions

  1. mcichecki created this gist Jun 23, 2018.
    19 changes: 19 additions & 0 deletions modInverse.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    /*
    given a and m, function finds x for a * x = 1 (mod m)

    24 * x = 1 (mod 5)
    24 = x*exp(-1) (mod 5)
    x = 4

    modInverse(a: 24, m: 5) returns optional(4)
    */

    func modInverse(a: Int, m: Int) -> Int? {
    let tmp = a % m
    for i in 1..<m {
    if (tmp * i % m == 1) {
    return i;
    }
    }
    return nil
    }