扩展欧几里得算法

  1. 在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务,要用git记录实现过程,git commit不能低于5次
  2. 严格按照《密码工程》p112伪代码实现ExtendedGCD(int a, int b, int *k, int *u, int *v)算法(10')
    2.根据ExtendedGCD 实现计算模逆元的函数int modInverse(int a, int m) ,返回a相对于m的模逆元(3‘)
  3. 在测试代码中计算74模167的模逆元。自己再设计至少两个类似测试代码。(2’)
  4. 提交代码和运行结果截图,git log截图
  5. 提交使用Markdown并转为pdf格式,或者使用doc、docx格式

image

image

#include <stdio.h>

// Extended GCD function from "Cryptography Engineering" (p112)
int extendedGCD(int a, int b, int *k, int *u, int *v) {
    int u1 = 1, u3 = a;
    int v1 = 0, v3 = b;
    int temp;

    while (v3 != 0) {
        int q = u3 / v3;
        temp = u1; u1 = v1; v1 = temp - q * v1;
        temp = u3; u3 = v3; v3 = temp - q * v3;
    }

    *k = u3;
    *u = u1;
    *v = (u3 - a * u1) / b;

    return u3;
}

// Function to calculate modular inverse
int modInverse(int a, int m) {
    int k, u, v;
    int gcd = extendedGCD(a, m, &k, &u, &v);

    if (gcd != 1) {
        printf("Inverse does not exist.\n");
        return -1;  // No modular inverse
    } else {
        // Ensure u is positive
        u = (u % m + m) % m;
        return u;
    }
}

int main() {
    int a = 74;
    int m = 167;

    // Calculate modular inverse of a modulo m
    int inverse = modInverse(a, m);

    if (inverse != -1) {
        printf("The modular inverse of %d modulo %d is: %d\n", a, m, inverse);
    }

    // Additional test cases
    int a2 = 17;
    int m2 = 31;

    int inverse2 = modInverse(a2, m2);

    if (inverse2 != -1) {
        printf("The modular inverse of %d modulo %d is: %d\n", a2, m2, inverse2);
    }

    int a3 = 15;
    int m3 = 26;

    int inverse3 = modInverse(a3, m3);

    if (inverse3 != -1) {
        printf("The modular inverse of %d modulo %d is: %d\n", a3, m3, inverse3);
    }

    return 0;
}

posted @ 2024-06-03 08:34  20211108俞振阳  阅读(7)  评论(0编辑  收藏  举报