Realloc initially works for array sizes 200 and 400, but then unexpectedly returns null at size 800 for reasons I cannot parse.
Unsigned long ints in use because of that massive m value and are very much necessary. Probably.
I'm embarrassingly bad at C.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Macros */
#define m 4294967161
#define a 2
#define r (m % a)
#define q (unsigned long) floor(m / a)
/* Method stubs */
[snip]
/* Initial array settings */
unsigned long elements = 0; // Number of elements in the array.
unsigned long size = 100; // Dynamically allocated size of the array.
/* Evaluates g(x) = ax mod m with no values > m - 1 */
unsigned long g(unsigned long x) {
[snip]
}
unsigned long compute() {
unsigned long i = 1;
unsigned long x = a;
unsigned long j = 0;
unsigned long *multipliers = 0;
initialize(&multipliers);
while (x != 1) {
if (((m % x) < (m / x)) && (gcd(i, m - 1) == 1)) {
add(x, multipliers);
j++;
}
i++;
x = g(x);
}
}
/* Initialize array. */
void initialize(unsigned long **multipliers) {
*multipliers = (unsigned long *)malloc(sizeof(unsigned long) * size);
}
/* Add element to an array. */
void add(unsigned long element, unsigned long *multipliers) {
if (elements >= size) {
printf("Inside elements >= size check.\n");
size = size * 2;
printf("Size is now %lu\n", size);
unsigned long *n_vector = NULL;
n_vector = (unsigned long *)realloc(multipliers, sizeof(unsigned long) * size);
printf("Reallocated.\n");
if (n_vector != NULL) {
printf("Copying n_vector to multipliers.\n");
multipliers = n_vector;
}
else
printf("n_vector is null.\n");
}
multipliers[elements++] = element;
return;
}