tags:

views:

63

answers:

2

i know that horners method for polynomial pultiplication is faster but here i dont know what is happening here is code

public class horner{

  public static  final  int n=10;
  public static  final  int x=7;

  public static void main(String[] args){
    //non fast version
    int a[]=new int[]{1,2,3,4,5,6,7,8,9,10};
    int xi=1;
    int y=a[0];
    for (int i=1;i<n;i++){
      xi=x*xi;
      y=y+a[i]*xi;
    }
    System.out.println(y);
    //fast method
    int y1=a[n-1];
    for (int  i=n-2;i>=0;i--){
      y1=x*y+a[i];
    }

    System.out.println(y1);
  }
}

result of this two methods are not same result of first method is

462945547

and result of second method is

-1054348465

please help

A: 

Look at this loop:

for (int i=1;i<n;i++){ 
            xi=x*xi; 
            y=y+a[i]*xi; 
        } 

I think you should use

for (int i=0;i<n;i++){ 
            xi=x*xi; 
            y=y+a[i]*xi; 
        } 
J Angwenyi
no first is correct second is mistake
+2  A: 

You're using y on the second loop:

y1=x*y+a[i];

This is where writing two function would come in handy - it would be impossible to reuse the same variable.

Kobi
thanks sorry cool mistake thanks Kobi i did not pay attention