/*=============================================================================
Filename: logarithms.c
Purpose : approximates e using two different methods
Author  : Tristan Miller -- psy@cs.toronto.edu

Study questions:
  * It would be nice to see more decimal places in the output.  Type
    "man 3c printf" at the Unix prompt or consult your C book to find out
    how to increase the precision of the printf() function.
=============================================================================*/

#include <stdio.h>
#include <stdlib.h>

#define N 25

double find_e1(unsigned n);
double find_e2(unsigned n);
double pow(double x, unsigned y);
unsigned factorial(unsigned n);

/* Compute e as (1 + 1/n)^n */
double find_e1(unsigned n) {
  return pow(1.0 + 1.0 / n, n);
}

/* Compute e from the series 1/0! + 1/1! + 1/2! + 1/3! + ... */
double find_e2(unsigned n) {
  double result = 1.0;

  while (n--)
    result += 1.0 / factorial(n);

  return result;
}

/* Compute x^y (for non-negative integer y) */
double pow(double x, unsigned y) {
  double result = x;
  while (--y)
    result *= x;
  return result;
}

/* Compute n! */
unsigned factorial(unsigned n) {
  if (n <= 1)
    return 1;
  return n * factorial(n - 1);
}

/* ------------------------------ main() ------------------------------ */
int main(void) {

  int n;

  printf("n=0\tMethod 1: n/a\t\tMethod 2: %f\n", find_e2(0));

  for (n = 1; n < N; n++)
    printf("n=%d\tMethod 1: %f\tMethod 2: %f\n", n, find_e1(n),
	   find_e2(n));

  return EXIT_SUCCESS;
}

