Kasra Ghavami
Kasra Ghavami

Reputation: 17

How to print an polynomial equation

I want to print a polynomial equation that I have the coefficients of it in an array. Each index of coefficient in array is the power of n in that array. For example, if the array is {17,11,1,13} the equation is 13*n^3+n^2+11*n+17. That format of that equation is exactly what I want to print. I have tried this, but it doesn't print anything if the equation is 0. For some of the other test cases there are some faults.

for (int i = 10; i > 0; i--) {
    if (array[i] == 0) {
        continue;
    }

    if (array[i] == 1) {
        if (i == 0 || i == 1) {
            if (i == 1) {
                System.out.print("n+");
            } else {
                System.out.print(array[i]);
            }
        }
        if (i > 1) {
            System.out.print("n^" + i + "+");
        }
    }if (array[i] > 1) {
        if (i == 0 || i == 1) {
            if (i == 1) {
                System.out.print(array[i] + "*n");

            } else {
                System.out.print(array[i]);
            }
        }
        if (i > 1) {
            System.out.print(array[i] + "*n^" + i );
            if (array[i-1]>0) {
                System.out.print("+");
            }
        }
    }

}

Upvotes: 0

Views: 2528

Answers (1)

Jeff Musser
Jeff Musser

Reputation: 121

int[] array = {17,11,1,13};
string polynomialString = "";
for(int i = array.length - 1; i >= 0; i--)
{
  if(i > 1)
  {
    polynomialString += array[i] + "*n^" + i + "+";
  }
  else if(i == 1)
  {
    polynomialString += array[i] + "*n+";
  }
  else
  {
    polynomialString += array[i];
  }
}
return polynomialString;

Upvotes: 2

Related Questions