/*
   This file is part of Numerix.  Numerix is free software; you can
   redistribute it and/or modify it under the terms of the GNU General
   Public License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
   USA 
*/

	/* +---------------------------------------------------+
	   |  Démonstration de la bibliothèque Numerix avec C  |
	   +---------------------------------------------------+ */

/* calcul de (sqrt(3) + sqrt(2))/(sqrt(3)-sqrt(2)) avec n décimales */
/* M. Quercia, le 31/01/2001 */

#include <stdlib.h>
#include <stdio.h>
#include "c-long_int.h"

void calcul(xint *res, long n) {
   xint dix_n  = xx(new)();
   xint dix_2n = xx(new)();
   xint sqrt_2 = xx(new)();
   xint sqrt_3 = xx(new)();
   xint x      = xx(new)();
   xint y      = xx(new)();

   xx(copy_int)(&dix_n,5);
   xx(pow)  (&dix_n,  dix_n,  n);       /* dix_n <- 5^n ...      */
   xx(shl)  (&dix_n,  dix_n,  n);       /*        ... * 2^n      */
   xx(sqr)  (&dix_2n, dix_n);           /* dix_2n <- 10^(2n)     */
   xx(mul_1)(&sqrt_2, dix_2n, 200);     /* sqrt_2 <- ...         */
   xx(sqrt) (&sqrt_2, sqrt_2);          /* .. sqrt(2*10^(2n+2))  */
   xx(mul_1)(&sqrt_3, dix_2n, 300);     /* sqrt_3 <- ...         */
   xx(sqrt) (&sqrt_3, sqrt_3);          /* .. sqrt(3*10^(2n+2))  */
   xx(add)  (&x,      sqrt_3, sqrt_2);  /* x <- sqrt_3 + sqrt_2  */
   xx(sub)  (&y,      sqrt_3, sqrt_2);  /* y <- sqrt_3 - sqrt_2  */
   xx(mul)  (&x,      dix_n,  x);       /* res <- trunc(10^n*x...*/
   xx(quo)  (res,     x,      y);       /*               ... /y) */
   
   xx(free)(&dix_n);
   xx(free)(&dix_2n);
   xx(free)(&sqrt_2);
   xx(free)(&sqrt_3);
   xx(free)(&x);
   xx(free)(&y);
}


int main(int argc, char **argv) {
  long n = 30;
  xint x = xx(new)();
  char *s;

  for(argc--, argv++; (argc); argc--, argv++) {
    if      (strcmp(*argv,"-test") == 0) {n = 30;}
    else if ((strcmp(*argv,"-n") == 0) && (argc > 0)) {
      argc--, argv++;
      n = atol(*argv);
    } else {
      fprintf(stderr,"syntaxe : simple [-test] [-n <n>]\n");
      fflush(stderr);
      exit(1);
    }
  }

  calcul(&x,n);
  s = xx(string_of)(x);
  fprintf(stdout,"%s\n",s);
  fflush(stdout);

  xx(free)(&x);
  xx(free_string)(s);
  return(0);
}

               
