#include <iostream>
#include "wielomian.h"
using namespace std;

Wielomian::Wielomian()
{
	st=0;
	wsp=new double[1];
	*wsp=0;
}

Wielomian::Wielomian(int st, double *wsp)
{
	this->st=st;
	this->wsp=new double[st+1];
	for(int i=0; i<=st; i++)
		this->wsp[i] = wsp[i];
}

Wielomian::Wielomian(const Wielomian & w)
{
	this->st=w.st;
	wsp=new double[st+1];
	for(int i=0; i<=st; i++)
		wsp[i]=w.wsp[i];
}


Wielomian Wielomian::Pochodna(int k) const
{
   if(k > st) 
   {
      Wielomian w;
      return w;
   }

	if (k == 1)
	{
		Wielomian w(this->st-1, this->wsp);
		for (int i = st; i > 0; i--)
			w.wsp[i-1] = this->wsp[i] * i;

		return w;
	}
	return Pochodna(1).Pochodna(k-1);
}

void Wielomian::Wypisz() const
{
	cout << *this; 
}

Wielomian::~Wielomian()
{
	delete [] wsp;
}

Wielomian& Wielomian::Wczytaj()
{
   int st;
   cout << "Stopien wielomianu ?" << endl ;
   cin >> st;
   if (st != this->st)
   {
      this->st=st;
      delete [] wsp;
      this->wsp=new double[st+1];
   }

   for(int i=st; i>=0; i--)
   {
      cout << "a[" << i << "]= " ;
      cin >> this->wsp[i];
   }
   return *this;
}

ostream &operator<<(ostream &o, const Wielomian &w)
{
	o << "f(x) = ";
	for(int i=w.st; i>0; i--)
		if(w.wsp[i]!=0) 
		{
			 if(w.wsp[i]!=1.0) o << showpos << w.wsp[i] << noshowpos ;
			 if(i!=1) o << " x^"  << i  << " "; 
             else  o << " x " ;
		}
	
	if (w.wsp[0]!=0 || w.st==0) o << showpos << w.wsp[0] << noshowpos ;
	return o;
}

Wielomian Wielomian::operator+(const Wielomian &w) const
{
	int max = this->st > w.st ? this->st : w.st;
	double *tmp = new double[max+1];
	for (int i = 0; i <= max; i++) tmp[i] = 0.0;
	for (int i = 0; i <= this->st ; i++) tmp[i] = this->wsp[i];
	for (int i = 0; i <= w.st ; i++) tmp[i] += w.wsp[i];
	Wielomian wout(max, tmp);
	delete [] tmp;
	return wout;
}

double Wielomian::operator()(double x) const
{
	double y = wsp[st];
	for (int i = st-1; i >= 0 ; i--)
		y = x * y + wsp[i];
	return y;
}

Wielomian &Wielomian::operator=(const Wielomian &w)
{
	if (st != w.st)
	{
	   st = w.st;
		delete [] wsp;
		wsp = new double[w.st+1];
	}

	for (int i = 0; i < st +1; i++)
		wsp[i] = w.wsp[i];

	return *this;
}






