]> www.ginac.de Git - cln.git/blob - examples/contfrac.cc
f93f869e4f8be860efa33dff5837c2508e7c40fb
[cln.git] / examples / contfrac.cc
1 // Print the continued fraction of a real number.
2
3 // We work with real numbers and integers.
4 #include <cl_real.h>
5 #include <cl_integer.h>
6
7 // We do I/O.
8 #include <cl_io.h>
9 #include <cl_integer_io.h>
10
11 // Our private error handling: return to the main program.
12 #include <setjmp.h>
13 jmp_buf restartpoint;
14 void cl_abort (void) { longjmp(restartpoint,1); }
15
16 int main (int argc, char* argv[])
17 {
18         for (int i = 1; i < argc; i++) {
19                 const char * arg = argv[i];
20                 if (setjmp(restartpoint))
21                         continue;
22                 // Convert argument to its internal representation:
23                 cl_R x = arg;
24                 // Check sign.
25                 if (minusp(x)) {
26                         fprint(cl_stdout, "-");
27                         x = -x;
28                 }
29                 fprint(cl_stdout, "[");
30                 const char* separator = "; ";
31                 for (;;) {
32                         // Split x into integral and fractional part.
33                         cl_R_div_t x_split = floor2(x);
34                         fprint(cl_stdout, x_split.quotient);
35                         x = x_split.remainder;
36                         if (zerop(x))
37                                 break;
38                         fprint(cl_stdout, separator);
39                         separator = ", ";
40                         // Invert x.
41                         x = recip(x);
42                 }
43                 fprint(cl_stdout, "]\n");
44         }
45 }