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.
/**
** Java Program to implement Horner Algorithm
**/
import java.util.Scanner;
public class Horner
{
private int sum;
/** constructor **/
public Horner(int[] cof, int x)
{
sum = 0;
calcSum(cof, x, cof.length - 1);
display();
}
/** Calculate sum **/
private void calcSum(int[] cof, int x, int N)
{
sum = cof[N] * x;
for (int i = N - 1; i >= 1; i--)
sum = (sum + cof[i]) * x;
sum += cof[0];
}
public void display()
{
System.out.println("Evaluated sum = "+ sum);
}
/** main method **/
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Horner Algorithm Test\n");
System.out.println("Enter highest power");
int n = scan.nextInt();
int[] arr = new int[n + 1];
System.out.println("\nEnter "+ (n + 1) +" coefficients in increasing order");
for (int i = 0; i <= n; i++)
arr[i] = scan.nextInt();
System.out.println("\nEnter x");
int x = scan.nextInt();
Horner h = new Horner(arr, x);
}
}
Output:
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
Related posts:
Java TreeMap vs HashMap
Java Program to Implement Hash Tables chaining with Singly Linked Lists
Number Formatting in Java
Java Program to Generate a Random Subset by Coin Flipping
Testing an OAuth Secured API with Spring MVC
Java Program to Create the Prufer Code for a Tree
Java Program to Find Path Between Two Nodes in a Graph
Spring Boot - Unit Test Cases
Spring 5 Testing with @EnabledIf Annotation
Spring Security Logout
Java Program to Implement Shoelace Algorithm
The Difference Between map() and flatMap()
Java Program to Implement ArrayDeque API
Injecting Prototype Beans into a Singleton Instance in Spring
Receive email by java client
Registration – Password Strength and Rules
Java Program to Implement ArrayList API
Java Program to Implement Sieve Of Atkin
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Changing Annotation Parameters At Runtime
Giới thiệu Aspect Oriented Programming (AOP)
Java Program to Implement TreeSet API
Java Program to Implement HashMap API
Encode a String to UTF-8 in Java
Java Copy Constructor
Java Program to Implement the String Search Algorithm for Short Text Sizes
Handle EML file with JavaMail
Implementing a Binary Tree in Java
Java Program to Implement Coppersmith Freivald’s Algorithm
Java Program to Implement LinkedList API
A Guide to the ResourceBundle
Java Program to Implement HashTable API