密码工程-扩展欧几里得算法

  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格式
####myexgcd
#include<stdio.h>
int main()
{
    unsigned int a,b;
    int u,v,gcd;
    int extendedgcd(unsigned int a,unsigned int b,int *x,int *y);
    printf("请输入a和b:");
    scanf("%d%d",&a,&b);
    gcd=extendedgcd(a,b,&u,&v);
    printf("u=%d,v=%d\n",u,v);
    printf("最大公因子k=%d\n",gcd);
    printf("%d*%d+%d*%d=%d\n", u, a, v, b, gcd);
    return 0;
    }
    int extendedgcd(unsigned int a,unsigned int b,int *x,int *y)//扩展欧几里得算法;
    {
    if(b==0)
      {
        *x=1;
        *y=0;
        return a;
      }
    int ret=extendedgcd(b,a%b,x,y);
    int t=*x;
    *x=*y;
    *y=t-a/b*(*y);
    return ret;
}


git log截图


gitee链接
https://gitee.com/yogahuu/exptest

第二次尝试代码

###extendGCD.c
#include <stdio.h>

// Function to perform the extended Euclidean algorithm
void ExtendedGCD(int a, int b, int *k, int *u, int *v) {
    int u0 = 1, v0 = 0, u1 = 0, v1 = 1;
    int q, r, temp;
    while (b != 0) {
        q = a / b;
        r = a - q * b;
        a = b;
        b = r;

        temp = u0 - q * u1;
        u0 = u1;
        u1 = temp;

        temp = v0 - q * v1;
        v0 = v1;
        v1 = temp;
    }

    *k = a;   // gcd(a, b)
    *u = u0;  // Coefficient for a
    *v = v0;  // Coefficient for b
}

int main() {
    int a, b, k, u, v;
    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);

    ExtendedGCD(a, b, &k, &u, &v);
    printf("GCD: %d\n", k);
    printf("Coefficients: u = %d, v = %d\n", u, v);

    return 0;
}

exgcd3.c


#include <stdio.h>

// Function to perform the extended Euclidean algorithm
int ExtendedGCD(int a, int b, int *x, int *y) {
    if (b == 0) {
        *x = 1;
        *y = 0;
        return a;
    }

    int x1, y1; // To store results of recursive call
    int gcd = ExtendedGCD(b, a % b, &x1, &y1);

    // Update x and y using results of recursive call
    *x = y1;
    *y = x1 - (a / b) * y1;

    return gcd;
}

// Function to find modular inverse of a under modulo m
// Assuming m is prime
int modInverse(int a, int m) {
    int x, y;
    int gcd = ExtendedGCD(a, m, &x, &y);
    if (gcd != 1) {
        printf("Inverse does not exist\n");
        return -1; // Inverse doesn't exist
    } else {
        // m is added to handle negative x
        int res = (x % m + m) % m;
        return res;
    }
}

int main() {
    int a, m;
    printf("Enter a and m: ");
    scanf("%d %d", &a, &m);

    int inverse = modInverse(a, m);
    if (inverse != -1)
        printf("The modular inverse is %d\n", inverse);
    else
        printf("No modular inverse exists.\n");

    return 0;
}



posted @ 2024-06-03 08:12  20211211  阅读(26)  评论(0)    收藏  举报