Created
April 9, 2019 20:32
-
-
Save masterzorag/6a5fb724fd5c2d15ef57d2184449692f to your computer and use it in GitHub Desktop.
gmp sample to compute square roots
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <gmp.h> | |
int main(int argc, char *argv[]) | |
{ | |
mpz_t x, t, prev, dif; | |
mpz_init(dif); | |
mpz_init(t); | |
mpz_init(prev); | |
int base = atoi(argv[1]); | |
mpz_set_str (t, argv[2], base); // | |
mpz_set(dif, t); | |
mpz_sqrt(t, t); | |
mpz_add_ui(prev, t, 0); | |
mpz_mul(prev, prev, prev); | |
//gmp_printf ("prev: %Zd\n", prev); | |
printf("base: %d, prev perfect sq:\n", base); | |
mpz_out_str(stdout, base, prev); printf("\n"); | |
gmp_printf ("sq: %Zd\n", t); | |
mpz_add_ui(t, t, 1); | |
mpz_mul(t, t, t); | |
gmp_printf ("next psq: %Zd\n", t); | |
gmp_printf ("next psq: in hex:\n%ZX\n", t); | |
///////////////////////// | |
mpf_t sq_me, sq_out, test; | |
mpf_set_default_prec (10000); | |
mpf_init(sq_me); | |
mpf_init(sq_out); | |
mpf_init(test); | |
mpf_set_str (sq_me, argv[2], atoi(argv[1])); | |
mpf_sqrt(sq_out, sq_me); | |
mpf_mul(test,sq_out,sq_out); | |
gmp_printf ("Input: %Ff\n\n", sq_me); | |
gmp_printf ("Square root: %.200Ff\n\n", sq_out); | |
gmp_printf ("Re-squared: %Ff\n\n", test); | |
gmp_printf ("dif: %Zd - %Zd\n", t, dif); | |
mpz_sub(dif, t, dif); | |
gmp_printf ("dif: %Zd\n", dif); | |
/* memleaks, how clear mpf? | |
mpz_clear(sq_me); | |
mpz_clear(sq_out); | |
mpz_clear(test);*/ | |
//mpz_clear(x); | |
mpz_clear(t); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment