3

I am making a program to calculate operations over polynomials and I already finished other operation (+ - *) but stucked with the division, I am getting this error always as it shown in the code

static int[] DividePolnomials(int[] pol1, int[] pol2)
{
    int tmp = 0;
    int power_tmp = 0;
    int[] result_tmp;
    int[] result;
    if (pol1.Length > pol2.Length)
    {
        result = new int [pol1.Length];
        result_tmp = new int[pol1.Length];
        for (int i = 0; pol2.Length<=pol1.Length; i++)
        {

            if (pol2[pol2.Length-i-1] == 0) // here is the problem it gives that the index is outside the bounds
            {
                continue;
            }
            else
            {
                tmp = pol1[pol1.Length - i - 1] / pol2[pol2.Length - i - 1];
                power_tmp = (pol1.Length - i - 1) - (pol2.Length - i - 1);
                result[power_tmp] = tmp;
                result_tmp = Multiply(result, pol2);
                pol1 = SubtractPolnomial(pol1, result_tmp);
            }

        }
    }
    else
    {

        result = new int [pol1.Length];
    }
    return result;
}

I haven't completed all other scenarios in the code yet due to this error, but I would like to get any help in the case the two polynomials are equals in length

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
Omar
  • 98
  • 2
  • 12
  • Do you mean *integer* division and *remainder*? e.g. `1 / (x + 1)` should return `0` (and `x + 1` should be a remainder) – Dmitry Bychenko Feb 09 '16 at 06:46
  • I am trying to apply long division polynomial as it is here http://www.purplemath.com/modules/polydiv2.htm – Omar Feb 09 '16 at 06:57

1 Answers1

3

Your i becomes greater than pol2.Length-1, so at this moment you have pol2[-1], pol2[-2] etc. This does not allowed in C#. You can check the next statement:

       if ((pol2.Length-i-1 < 0) || (pol2[pol2.Length-i-1] == 0)) 
       {
           continue;
       }

EDIT: If the first condition is true, the second one will not be evaluated https://msdn.microsoft.com/en-us/library/6373h346.aspx

Pavel the coder
  • 565
  • 4
  • 18