From 62439387e5c78a09b86dd28fe1f47828ccc2cf6f Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Wed, 12 Feb 2025 20:51:51 +0100 Subject: [PATCH] Extended euclidean algorithm using recursion --- rsa.c | 17 +++++++++++++++++ rsa.h | 15 +++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/rsa.c b/rsa.c index b9c623a..06774fc 100644 --- a/rsa.c +++ b/rsa.c @@ -13,6 +13,23 @@ int gcd(int a, int b) { return a; } +int extended_euclid(int a, int b, int *x, int *y) { + if (b == 0) { + *x = 1; + *y = 0; + return a; + } + + int x1, y1; + int gcd = extended_euclid(b, a % b, &x1, &y1); + + // Update x and y using results from recursive call + *x = y1; + *y = x1 - (a / b) * y1; + + return gcd; +} + int totient(int n) { int result = n; diff --git a/rsa.h b/rsa.h index 9111722..690d0e3 100644 --- a/rsa.h +++ b/rsa.h @@ -65,3 +65,18 @@ bool is_prime(int n); * @return true if n is probably prime, false if n is composite. */ bool miller_rabin(int n, int k); + +/** + * @brief Computes the greatest common divisor (GCD) of two integers a and b + * using the Extended Euclidean Algorithm. Also finds coefficients x and y such + * that ax + by = gcd(a, b). + * + * @param a The first integer. + * @param b The second integer. + * @param x Pointer to an integer to store the coefficient x in the equation ax + * + by = gcd(a, b). + * @param y Pointer to an integer to store the coefficient y in the equation ax + * + by = gcd(a, b). + * @return The greatest common divisor (gcd) of a and b. + */ +int extended_euclid(int a, int b, int *x, int *y);