/* This file provides an implementation for library MyMath.

   Names defined:
      Sum(), a summation function
      Polynomial(), a polynomial calculating function
------------------------------------------------------------------*/

/*-------------------------------------------------------------------
   This function computes the summation from 1 to N, using a
   for loop.

   Receive:  An integer N
   Return:   Tthe value 1 + 2 + ... + N
--------------------------------------------------------------------*/

/*
int Sum(int N)
{
   int
      RunningTotal = 0;

   for (int Counter = 1; Counter <= N; Counter++)
      RunningTotal += Counter;

   return RunningTotal;
}
*/

/*-------------------------------------------------------------------
   This function computes the summation from 1 to N,
   using Gauss' formula.

   Receive:  An integer N
   Return:   The value 1 + 2 + ... + N
--------------------------------------------------------------------*/

int Sum(int N)
{
   return N * (N + 1) / 2;
}

/*-------------------------------------------------------------------
   This function will evaluate any polynomial, up to degree 4.

   Receive: The real values X, a, b, c, d, and e
   Return:  The real value a + bX + cX^2 + dX^3 + eX^4
--------------------------------------------------------------------*/
/*
#include <math.h>

double Polynomial(double X, double a, double b,
                  double c, double d, double e)
{
   return a + b*X + c*pow(X, 2.0) + d*pow(X, 3.0) + e*pow(X, 4.0);
}
*/
/*-------------------------------------------------------------------
   This function will evaluate a polynomial of any degree.

   Receive: The int Degree, a real value X, and the real
            coefficients a, ... of a polynomial
   Return:  The real value of the polynomial at X
--------------------------------------------------------------------*/

#include <stdarg.h>

double Polynomial(int Degree, double X, double a, ...)
{
   double
      PowerOfX = 1,                       // powers of X
      NextCoef,                           // next coefficient
      PolyValue = a;                      // polynomial's value at X

   va_list
      ArgList;

   va_start(ArgList, a);                  // ArgList begins after a

   for (int i = 1; i <= Degree; i++)
   {
      PowerOfX *= X;                      // i-th power of X
      NextCoef = va_arg(ArgList, double); // get the ith coefficient

      PolyValue += NextCoef * PowerOfX;   // ith term of polynomial
   }

   va_end(ArgList);                       // clean up the list

   return PolyValue;
}

