working quick_pow dec_to_bin

This commit is contained in:
2026-03-20 08:56:09 +01:00
parent 8851135394
commit 1eaae9ca4a
2 changed files with 94 additions and 1 deletions

1
build.sh Executable file
View File

@@ -0,0 +1 @@
gcc main.c -o main -std=c11 -lm && ./main

94
main.c
View File

@@ -1,6 +1,98 @@
#include <inttypes.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
int *dec_to_bin(int d, int *length) {
int *binary_form = calloc(20, sizeof(int));
int index = 0;
while (d != 0) {
binary_form[index] = d % 2;
d /= 2;
index++;
}
*length = index;
for (int i = index; i >= 0; i--) {
printf("%d", binary_form[i]);
}
printf(" index: %d\n", index);
return binary_form;
}
uint64_t quick_pow(int *d_binary, int a, int n, int length) {
uint64_t *powed = calloc(20, sizeof(uint64_t));
powed[0] = a;
for (int i = 1; i <= length; i++) {
powed[i] = (powed[i - 1] * powed[i - 1]) % n;
printf("powed: %ju, index: %d; ", powed[i], (i));
}
// check where in the binary are ones
uint64_t multiplied = 1;
for (int i = 0; i < length; i++) {
if (d_binary[i] == 1) {
multiplied *= powed[i];
}
}
printf("\nbm quick math: %ju; %d ", multiplied, n);
multiplied = multiplied % n;
printf("quick math: %ju", multiplied);
free(powed);
return multiplied;
}
bool prime_test(uint64_t n) {
printf("\n\nprime test: %jd\n", n);
// Miller Rabin prime test
// choose a base: a, which should be a prime so that (n, a) = 1
// then do 2 rounds of tests provided the first one did not fail
// 1: a^d =k 1 mod n
// 2: a^(d * 2^r) =k n-1 mod n
// d = n-1 / 2^S (where S means how many time did we divide the number till we reached the first odd number)
// S: see above
// r = {0,... S-1}
int a = 2;
int d = n - 1;
int S = 0;
int r = S - 1; // this stores the number of elements from 0 to S-1
while (d % 2 == 0) {
d = floor((double)d / 2.0);
S++;
printf("%d ", d);
}
printf("S: %d", S);
printf("\n");
// round 1
// 1: a^d =k 1 mod n
int length;
int *d_binary = dec_to_bin(d, &length);
if (quick_pow(d_binary, a, n, length) == 1) {
free(d_binary);
return true;
}
printf("\n\n");
free(d_binary);
return false;
}
int main() { int main() {
printf("Hello world!"); prime_test(111);
prime_test(29);
prime_test(27);
return 0; return 0;
} }