#pragma once
#include <stdbool.h>
#include <stdint.h>

/**
 * @brief Calculates greatest common divider of two integers using the euclidean
 * algorithm
 *
 * @param a First number
 * @param b Second number
 * @return The greatest common divider
 */
uint64_t gcd(uint64_t a, uint64_t b);

/**
 * @brief Computes Euler's Totient function φ(n), which counts the number of
 *        integers from 1 to n that are coprime to n.
 *
 * @param n The input number.
 * @return The number of integers from 1 to n that are coprime to n.
 */
int totient(int n);

/**
 * @brief Computes (a * b) % m safely without overflow.
 *
 * Uses repeated addition and bit shifting to handle large values,
 * ensuring correctness even on 32-bit microcontrollers.
 *
 * @param a The first operand.
 * @param b The second operand.
 * @param m The modulus.
 * @return (a * b) % m computed safely.
 */
uint64_t mulmod(uint64_t a, uint64_t b, uint64_t m);

/**
 * @brief Modular exponentiation (a^b) mod m
 *
 * @param a The base
 * @param b The exponent
 * @param m The modulus
 */
uint64_t modexp(uint64_t a, uint64_t b, uint64_t m);

/**
 * @brief Computes the modular inverse of a modulo m.
 *
 * @param a The integer whose modular inverse is to be found.
 * @param m The modulus.
 * @return The modular inverse of a modulo m, or -1 if no inverse exists.
 */
uint64_t mod_inverse(uint64_t a, uint64_t m);

/**
 * @brief Generates a random prime number within the given range.
 *
 * @param min The lower bound (inclusive).
 * @param max The upper bound (inclusive).
 * @return A prime number in the range [min, max].
 */
uint64_t gen_prime(uint64_t min, uint64_t max);

/**
 * @brief Checks if a number is prime.
 *
 * @param n The number to check.
 * @return true if n is prime, false otherwise.
 */
bool is_prime(int n);

/**
 * @brief Performs the Miller-Rabin primality test to check if a number is
 * probably prime.
 *
 * @param n The number to test for primality.
 * @param k The number of rounds of testing to perform.
 * @return true if n is probably prime, false if n is composite.
 */
bool miller_rabin(uint64_t n, uint64_t 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);