How to Add Polynomials in Java

Java, like many other programming languages, can perform various mathematical operations. However, more complex operations involving polynomials require the programmer to understand a certain process or equation, and write that equation in such a way as to allow Java to perform it. When adding polynomials, the important thing to understand is that the program should add the coefficients of the variables, while leaving the exponents untouched.

Things You'll Need

  • Java Development Kit
  • Text Editor or IDE
Show More

Instructions

    • 1

      Create a main class polynomial:

      class Polynomial{

      public static void main(String[] args){

      }
      }

    • 2

      Create two arrays in the main function, which will represent two polynomials.

      int[] first = new int[10]; //arrays are size 10, but can be any size depending on polynomial
      int[] second = new int[10];

    • 3

      Read user input for the coefficients and exponents of the polynomials. The user will enter integers in pairs: first, the coefficient, second the exponent:

      Scanner scan = new Scanner(System.in);

      int i = 0;

      for (i; i < 10; i+2){

      first[i] = scan.nextInt();
      first[i+1] = scan.nextInt();
      }

      i = 0;

      for (i; i < 10; i+2){

      second[i] = scan.nextInt();
      second[i+1] = scan.nextInt();
      }

    • 4

      Add the polynomials through the arrays:

      int j = 0;

      for (j; j < 10; j+2){

      int c = first[j] + second[j];

      System.out.print(c + "x^" + first[j+1] + "+");
      }

Related Searches:

References

Comments

Related Ads

Featured