#include <stdio.h>
#include<math.h>
/* 
   How to run the code from a terminal
   gcc main.c -o demo
   ./demo
 */

// declare global variables here (if any)
// define your own functions
void Ex4()
{
  printf("\nExercise 4.\n");
  int m=1, n=0;
  while (n<=m)
    {
      printf("Input m<n: ");
      scanf("%d %d",&m, &n);
    }
  printf("m=%d, n=%d\n",m,n);
  for (int i=1; i<=n; i++)
    {
      int reminder = i%m;
      if (reminder == 0)
	{
	  printf("%d ",i);
	}
    }
  printf("\n");
}

void Ex5()
{
  printf("\nExercise 5. Exchange money.\n");
  int ncents;
  int values[5]={50, 20, 10, 5, 1}; // intialize an array                                    
  printf("How many cents you want to change? ");
  scanf("%d",&ncents);
  for (int i=0; i<5; i++)
    {
      int n = ncents/values[i]; // get the integer part of the division                        
      ncents = ncents - n*values[i]; // get the remainder                                      
      printf("%d: %d\n",n,values[i]);
      if (ncents==0)
	{
	  break;
	}
    }
}

long int factorial(int n)
{
  long int r;
  if (n==0)
  {
    r = 1;
  }  
  else
  {
    r = n*factorial(n-1);
  }
  return r;
}

double mypower(double x, int n)
{
  double r = 1.;
  for (int i=0; i<n; i++)
  {
    r = r*x;
  }
  return r;
}

double myexp(x, N)
{
  double s = 0;
  for (int n=0; n<N+1; n++)
  {
    s = s+mypower(x,n)/factorial(n);
  }
  return s;
}


long int fibo(int N)
{
  long int r;
  if (N==1 || N==2)
  {
    r = 1;
  }
  else 
  {
    r = fibo(N-1)+fibo(N-2);
  }
  return r;
}

double f(double x)
{
  double r = sqrt(x*x+1.);
  return r;
}
double Trape(double a, double b, int n)
{
  double s = 0;
  for (int k=0; k<n+1; k++)
  {
    double x = a + k*(b-a)/n;
    if (k==0 || k==n)
    {
      s = s + f(x);
    }
    else
    {
      s = s+2.*f(x);
    }
  }
  s = (b-a)/(2.*n)*s;
  return s;
}  

int main()
{
  // Exercise 4
  Ex4();

  // Exercise 5
  Ex5();

  // Exercise 9
  printf("Exercise 9\n");
  int N; double x;                                                                         
  printf("Input x, N: ");
  scanf("%lf %d", &x, &N);
  double val = myexp(x,N);
  printf("Approximation: exp(%.1f)=%.16f\n",x,val);
  printf("Error        : %e\n",fabs(exp(x)-val)); 

  // Exercise 10
  printf("\nExercise 10\n");
   for (int n=1; n<6; n++)                                                                 
   {                          
     printf("F(%d)=%ld\n",n,fibo(n));
   } 

  // Exercise 11.
   printf("\nExercise 11\n");
  double s=Trape(0, 1., 500);
  printf("Numerical int(sqrt(x^2+1),x=0..1)=%.16f\n",s);
  double exact_integration = 1./2.*(sqrt(2.)-log(sqrt(2)-1));
  printf("Exact     int(sqrt(x^2+1),x=0..1)=%.16f\n",exact_integration);

  printf("Error: %e\n",fabs(s-exact_integration));

  return 0;
}