using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Horner
{
    class Program
    {
        //here it all happens
        static double Horner(double[] coeffients, int degree, double value)
        {
            double result = coeffients[degree];
            for (int i = degree - 1; i >= 0; i--)
            {
                result = result * value + coeffients[i];
            }
            return result;
        }


        //Main function to exercise the above
        static void Main(string[] args)
        {
            //coefficient array
            double[] c = {0,0,0,0,0,0,0,0,0,0,0};   //degree 10 maximum
            //highest degree
            int d;
            //value to be evaluated
            double v;
            Console.WriteLine("HORNER polynomial evaluator.");
            Console.WriteLine();
            Console.Write("Enter degree of polynomial: ");
            d = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Fill in coefficients from low to high degree.");
            Console.WriteLine("Coefficients, a[0], a[1], ..., a[" + d.ToString() + "]");
            for (int i = 0; i <= d; i++)
            {
                Console.Write("Coefficient a[" + i.ToString() + "] = ");
                c[i] = Convert.ToDouble(Console.ReadLine());
            }
            Console.Write("Enter the value to be evaluated: ");
            v = Convert.ToDouble(Console.ReadLine());

            double r = Horner(c, d, v);
            Console.WriteLine("------------------------------------------------");
            Console.WriteLine("The calculated value for this polynomial is : {0}",r);

        }
    }
}
3
Contributors
3
Replies
22
Views
8 Years
Discussion Span
Last Post by ddanbe
1

I found here "good" source code in c# for Horner scheme:

private IEnumerable<int> getDivisors(int n)
{
    if (n == 0)
        return (IEnumerable<int>)new int[] { 0 };
    else
        return Enumerable.Range(-Math.Abs(n), 2 * Math.Abs(n) + 1)
            .Where(a => a != 0)
            .Where(a => (n % a) == 0);
}
private bool findRootWithHornerScheme(int[] coefficientsA, int x, out int[] coefficientsB)
{
    var lenght = coefficientsA.Length;
    var tmpB = new int[lenght];
    coefficientsB = new int[lenght - 1];
    tmpB[0] = coefficientsA[0];
    for (int i = 1; i < lenght; i++)
    {
        tmpB[i] = tmpB[i - 1] * x + coefficientsA[i];
    }
    //ak je posledny koefiecient B == 0 ,tak zadane x je korenom polynomu
    if (tmpB[lenght - 1] == 0)
    {
        Array.Copy(tmpB, coefficientsB, lenght - 1);
        return true;//bol najdeny koren
    }
    //nebol najdeny koren a metoda vrati false
    return false;
}
Comments
Nice!
0

My version was before LINQ was introduced in C#. The Rosetta code version uses LINQ in an excellent way.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.