Skip to content

Instantly share code, notes, and snippets.

@Enchufa2
Created July 30, 2021 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Enchufa2/aceea42d68d7f7cd7c4db4d8f71720b8 to your computer and use it in GitHub Desktop.
Save Enchufa2/aceea42d68d7f7cd7c4db4d8f71720b8 to your computer and use it in GitHub Desktop.
Collatz's conjecture + GMP games
#include <stdio.h>
#include <gmp.h>
int main() {
mpz_t x, y, odd_or_even;
mpz_init(x);
mpz_init(y);
mpz_init(odd_or_even);
unsigned long int i, p;
for (p = 69; p < 100000; p++) {
mpz_ui_pow_ui(x, 2, p);
mpz_sub_ui(x, x, 1);
mpz_set(y, x);
i = 0;
while (1) {
i += 1;
mpz_mod_ui(odd_or_even, y, 2);
if (mpz_get_ui(odd_or_even)) {
mpz_mul_ui(y, y, 3);
mpz_add_ui(y, y, 1);
} else {
mpz_cdiv_q_ui(y, y, 2);
}
if (mpz_cmp_ui(y, 1) == 0)
break;
else if (mpz_cmp(y, x) == 0)
goto finish; // optimism!
}
printf("%lu %lu\n", p, i);
}
finish:
printf("%lu ", p);
mpz_out_str(stdout, 10, y);
printf(" %lu\n", i);
mpz_clear(x);
mpz_clear(y);
mpz_clear(odd_or_even);
return 0;
}
#include <stdio.h>
#include <time.h>
#include <gmp.h>
int main() {
gmp_randstate_t state;
gmp_randinit_default(state);
gmp_randseed_ui(state, time(NULL));
mpz_t x, y, odd_or_even;
mpz_init(x);
mpz_init(y);
mpz_init(odd_or_even);
unsigned long int i;
while (1) {
mpz_urandomb(x, state, 1000);
mpz_set(y, x);
i = 0;
while (1) {
i += 1;
mpz_mod_ui(odd_or_even, y, 2);
if (mpz_get_ui(odd_or_even)) {
mpz_mul_ui(y, y, 3);
mpz_add_ui(y, y, 1);
} else {
mpz_cdiv_q_ui(y, y, 2);
}
if (mpz_cmp_ui(y, 1) == 0)
break;
else if (mpz_cmp(y, x) == 0)
goto finish; // optimism!
}
//printf(" %lu\n", i);
}
finish:
mpz_out_str(stdout, 10, y);
printf(" %lu\n", i);
mpz_clear(x);
mpz_clear(y);
mpz_clear(odd_or_even);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment