Skip to content

Instantly share code, notes, and snippets.

@MurageKibicho
Created March 2, 2025 16:43
Show Gist options
  • Save MurageKibicho/b8ce913f526e6471e82a939e45ea895b to your computer and use it in GitHub Desktop.
Save MurageKibicho/b8ce913f526e6471e82a939e45ea895b to your computer and use it in GitHub Desktop.
Find Generators of a fiel mod a prime number in C
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// Function to compute (base^exp) % mod using fast modular exponentiation
long long mod_exp(long long base, long long exp, long long mod) {
long long result = 1;
while (exp > 0) {
if (exp % 2 == 1) result = (result * base) % mod;
base = (base * base) % mod;
exp /= 2;
}
return result;
}
// Function to compute prime factors of n and store in factors[]
int prime_factors(int n, int factors[]) {
int count = 0;
while (n % 2 == 0) {
if (count == 0) factors[count++] = 2;
n /= 2;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
factors[count++] = i;
while (n % i == 0) n /= i;
}
}
if (n > 1) factors[count++] = n;
return count;
}
// Function to check if g is a generator mod p
int is_generator(int g, int p, int phi, int factors[], int num_factors) {
for (int i = 0; i < num_factors; i++) {
//printf("%3d %3d\n", g, phi / factors[i]);''
long long result = mod_exp(g, phi / factors[i], p);
//printf("|%3d,%3d,%3d| %d\n ", g, phi / factors[i],p, result);
if (result== 1) return 0;
}
return 1;
}
// Function to find all generators mod p
void find_generators(int p) {
int phi = p - 1;
int factors[20]; // Enough to store prime factors
int num_factors = prime_factors(phi, factors);
printf("Generators of %d: ", p);
for (int g = 2; g < p; g++) {
if (is_generator(g, p, phi, factors, num_factors)) {
printf("%d ", g);
}
}
printf("\n");
}
int main() {
int p = 13;
find_generators(p);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment