Java Program to Implement Horner Algorithm

This is a Java Program to Implement Horner Algorithm. Horner’s method is an efficient method for calculating polynomials.
Here is the source code of the Java Program to Implement Horner Algorithm. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /**
  2.  ** Java Program to implement Horner Algorithm
  3.  **/
  4.  
  5. import java.util.Scanner;
  6.  
  7. public class Horner
  8. {
  9.     private int sum;
  10.     /** constructor **/
  11.     public Horner(int[] cof, int x)
  12.     {
  13.         sum = 0;
  14.         calcSum(cof, x, cof.length - 1);
  15.         display();
  16.     }
  17.     /** Calculate sum **/
  18.     private void calcSum(int[] cof, int x, int N)
  19.     {
  20.         sum = cof[N] * x;
  21.         for (int i = N - 1; i >= 1; i--)
  22.             sum = (sum + cof[i]) * x;
  23.         sum += cof[0];
  24.     }
  25.     public void display()
  26.     {
  27.         System.out.println("Evaluated sum = "+ sum);
  28.     }
  29.     /** main method **/
  30.     public static void main(String[] args) 
  31.     {
  32.         Scanner scan = new Scanner(System.in);
  33.         System.out.println("Horner Algorithm Test\n");
  34.         System.out.println("Enter highest power");
  35.         int n = scan.nextInt();
  36.         int[] arr = new int[n + 1];
  37.         System.out.println("\nEnter "+ (n + 1) +" coefficients in increasing order");
  38.         for (int i = 0; i <= n; i++)
  39.             arr[i] = scan.nextInt();
  40.         System.out.println("\nEnter x");
  41.         int x = scan.nextInt();
  42.         Horner h = new Horner(arr, x);
  43.     }
  44. }

Horner Algorithm Test
 
Enter highest power
5
 
Enter 6 coefficients in increasing order
1 2 3 4 5 6
 
Enter x
2
Evaluated sum = 321

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

If you wish to look at all Java Programming examples, go to Java Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.