/*
   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 
*/

/* 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 <gmp.h>

void calcul(mpz_t res, long n) {
  mpz_t dix_n, dix_2n, sqrt_2, sqrt_3, x,y;
  mpz_init(dix_n);
  mpz_init(dix_2n);
  mpz_init(sqrt_2);
  mpz_init(sqrt_3);
  mpz_init(x);
  mpz_init(y);

  mpz_ui_pow_ui(dix_n,5,n);              /* dix_n <- 5^n ...      */
  mpz_mul_2exp(dix_n,  dix_n,  n);       /*        ... * 2^n      */
  mpz_mul     (dix_2n, dix_n,  dix_n);   /* dix_2n <- 10^(2n)     */
  mpz_mul_ui  (sqrt_2, dix_2n, 200);     /* sqrt_2 <- ...         */
  mpz_sqrt    (sqrt_2, sqrt_2);          /* .. sqrt(2*10^(2n+2))  */
  mpz_mul_ui  (sqrt_3, dix_2n, 300);     /* sqrt_3 <- ...         */
  mpz_sqrt    (sqrt_3, sqrt_3);          /* .. sqrt(3*10^(2n+2))  */
  mpz_add     (x,      sqrt_3, sqrt_2);  /* x <- sqrt_3 + sqrt_2  */
  mpz_sub     (y,      sqrt_3, sqrt_2);  /* y <- sqrt_3 - sqrt_2  */
  mpz_mul     (x,      dix_n,  x);       /* res <- trunc(10^n*x...*/
  mpz_fdiv_q  (res,    x,      y);       /*               ... /y) */
   
  mpz_clear(dix_n);
  mpz_clear(dix_2n);
  mpz_clear(sqrt_2);
  mpz_clear(sqrt_3);
  mpz_clear(x);
  mpz_clear(y);
}


int main(int argc, char **argv) {
  long n = 30;
  mpz_t x;
  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);
    }
  }

  mpz_init(x);
  calcul(x,n);
  s = mpz_get_str(NULL, 10, x);
  fprintf(stdout,"%s\n",s);
  fflush(stdout);

  mpz_clear(x);
  free(s);
  return(0);
}

               
