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

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

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

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

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

Wielomian Wielomian::Pochodna(int st)
{
   if(st==1)
   {

      Wielomian w;
      if(this->st>0)
      {
         w.st=this->st-1;
         delete [] w.wsp;
         w.wsp = new double [w.st+1];

         for(int i=0; i<=w.st; i++)   w.wsp[i]=this->wsp[i+1]*(i+1);
      }
      return w;
   }
   return Pochodna().Pochodna(st-1); //trik
}


Wielomian Wielomian::operator*()
{
   return this->Pochodna();
}

void Wielomian::Wyswietl()
{
/*
   for(int i=st; i>0; i--)
		if(wsp[i]!=0) 
			cout << wsp[i] << "x^" << i << " + ";
	
	cout << wsp[0] <<endl;
   */
   cout << *this << endl;
}

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

Wielomian Wielomian::operator+(const Wielomian &w)
{
   const Wielomian *max=this;
   const Wielomian *min=&w;
   if(max->st<min->st) 
   {
      max=&w;
      min=this;
   }
   Wielomian w2(*max);
   for(int i=0;i<=min->st;i++) w2.wsp[i]+=min->wsp[i];
   return w2;
}

Wielomian Wielomian::operator*(double x)
{
   Wielomian w(*this);
   int i=w.st;
   while(i>=0) w.wsp[i--]*=x;
   return w;
}

Wielomian &Wielomian::operator=(const Wielomian  &w)
{
   if(st!=w.st)
   {
      st=w.st;
      delete [] wsp;
      wsp = new double[st+1];
   }
   for(int i=0;i<=st;i++) wsp[i]=w.wsp[i];
   return *this;
}

Wielomian &Wielomian::operator*=(double x)
{
	return *this=*this*x;
}
   
   
ostream &operator<<(ostream &o,const Wielomian &w)
{
   o << "Wielomian " << w.st << " stopnia  f(x)= "; 
	for(int i=w.st; i>0; i--)
		if(w.wsp[i]!=0) 
			o << w.wsp[i] << "x^" << i << " + ";
	
	o << w.wsp[0];
   return o;
}
