Reputation:
Memory seems to run out when I run the executable from within the Visual Studio Code terminal, and then my computer freezes.
But all is fine when I run it from gnome terminal, and I get the desired outputs.
I'm not yet knowledgeable about c or the gmp.h library. I wouldn't be surprised if there is a bug somewhere, or something I am missing, even if the code I've posted does give me correct results when not run from VSCode.
Btw it does take about 1m43s to run, with N 666666, on my pc.
// problem from: https://www.reddit.com/r/dailyprogrammer/comments/jfcuz5/20201021_challenge_386_intermediate_partition/
#include "gmp.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define N 666666
mpz_t results[N + 1];
void segment(int n)
{
if (n <= 1)
return;
if (mpz_cmp_ui(results[n - 1], 0) > 0)
return;
mpz_t result;
mpz_t diff;
mpz_init(result);
mpz_init(diff);
int i = 0;
int seq = 1;
int is_positive;
while (n - seq >= 0)
{
segment(n - seq);
is_positive = 1 - 2 * (i / 2 % 2);
mpz_mul_si(diff, results[n - seq - 1], is_positive);
mpz_add(result, result, diff);
seq += (i % 2 > 0) ? i + 2 : (i + 2) / 2;
i += 1;
mpz_set_ui(diff, 0);
}
mpz_add_ui(results[n - 1], result, 0);
mpz_clear(result);
mpz_clear(diff);
return;
}
int main(void)
{
for (int i; i < N; i++)
{
mpz_init(results[i]);
}
mpz_set_ui(results[0], 1);
mpz_set_ui(results[1], 1);
for (int i; i <= N + 1; i++)
{
segment(i);
}
gmp_printf("Result: %Zd\n", results[N]);
for (int i; i < N; i++)
{
mpz_clear(results[i]);
}
}
Upvotes: 0
Views: 567
Reputation: 144989
The code has undefined behavior because the for
loops do not initialize the i
loop index: for (int i; i < N; i++)
Furthemore, the array has N + 1
elements, so the initialization loop should run one step farther and the segment loop one less.
Modify the main()
function to:
int main() {
for (int i = 0; i < N + 1; i++) {
mpz_init(results[i]);
}
mpz_set_ui(results[0], 1);
mpz_set_ui(results[1], 1);
for (int i = 0; i < N + 1; i++) {
segment(i);
}
gmp_printf("Result: %Zd\n", results[N]);
for (int i = 0; i < N + 1; i++) {
mpz_clear(results[i]);
}
return 0;
}
Upvotes: 1