Created
May 6, 2022 10:32
-
-
Save abiiranathan/06e38155e1953569882498b8e98332d1 to your computer and use it in GitHub Desktop.
C program to solve polynomials using Horner's algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Polynomial evaluation with Horner's method | |
#include <stdio.h> | |
#include <stdlib.h> | |
// poly is an array of coefficients | |
// n is the degree of the polynomial + 1 | |
// x is the value at which to evaluate the polynomial | |
// | |
// Returns value of poly[0]x(n-1) + poly[1]x(n-2) + .. + poly[n-1] | |
int horner(int poly[], int n, int x) | |
{ | |
int result = poly[0]; // Initialize result | |
// Evaluate value of polynomial using Horner's method | |
for (int i = 1; i < n; i++) | |
result = result * x + poly[i]; | |
return result; | |
} | |
int main() | |
{ | |
int n, x, *c; | |
printf("Enter the degree of the polynomial: "); | |
scanf("%d", &n); | |
c = (int *)malloc((n + 1) * sizeof(int)); | |
printf("Enter the coefficients of the polynomial: "); | |
for (int i = 0; i <= n; i++) | |
scanf("%d", &c[i]); | |
printf("Enter the value of x: "); | |
scanf("%d", &x); | |
printf("\nThe value of the polynomial is %d\n", horner(c, n + 1, x)); | |
free(c); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment