Added sign of a continued fraction.
[frac.git] / sqrt2.c
blob6109ff44d8ffd72d4592f3fcdf1cd092b342fd40
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <gmp.h>
4 #include "cf.h"
6 static void *sqrt2(cf_t cf) {
7 cf_put_int(cf, 1);
8 while(cf_wait(cf)) {
9 cf_put_int(cf, 2);
11 return NULL;
14 cf_t cf_new_sqrt2() {
15 return cf_new_const(sqrt2);
18 int main() {
19 cf_t x, conv;
20 x = cf_new_sqrt2();
21 conv = cf_new_convergent(x);
23 mpz_t p, q;
24 mpz_init(p);
25 mpz_init(q);
26 for (int i = 0; i < 10; i++) {
27 cf_get(p, conv);
28 cf_get(q, conv);
29 gmp_printf("p/q = %Zd/%Zd\n", p, q);
31 cf_free(conv);
32 cf_free(x);
34 x = cf_new_sqrt2();
35 mpz_t a, b, c, d;
36 mpz_init(a); mpz_init(b); mpz_init(c); mpz_init(d);
37 mpz_set_si(a, -7);
38 mpz_set_si(b, 5);
39 mpz_set_si(c, -12);
40 mpz_set_si(d, 13);
41 cf_t dec = cf_new_mobius_to_decimal(x, a, b, c, d);
42 cf_get(p, dec);
43 putchar(cf_sign(dec) > 0 ? ' ' : '-');
44 gmp_printf("%Zd.", p);
45 for (int i = 0; i < 10; i++) {
46 cf_get(p, dec);
47 gmp_printf("%Zd", p);
49 putchar('\n');
50 cf_free(x);
51 mpz_clear(p);
52 mpz_clear(q);
53 return 0;