2017年7月29日 星期六

(Java) 多項式

  1. /* 
  2.  * 多項式 
  3.  */  
  4. public class Polynomial {  
  5.   
  6.   public static void main(String[] args) {  
  7.              int[] a = {4,3,7,0,6,2};//第一種表示法 a[0] :項次 剩下微細數  
  8.              printPoly(a,"a1");  
  9.              int[] b = {5,-1,-5,2,0,9,4};  
  10.              printPoly(b,"b1");  
  11.              PolySum(a,b);  
  12.  }  
  13. static void printPoly(int[] poly,String name){  
  14.  System.out.print(name +": ");  
  15.  int max =  poly[0] ;//最高項次  
  16.  for(int i = 1 ; i <  poly.length ; i++){  
  17.   if(poly[i] != 0){//假如係數是0  
  18.    if(max != 0) System.out.print(poly[i] +"X^"+max+"+");  
  19.    else System.out.print(poly[i]); //0項次  
  20.    max--;  
  21.   }else{  
  22.    max--;  
  23.    continue ;  
  24.   }  
  25.  }  
  26.  System.out.println();  
  27. }  
  28. static void PolySum(int[] poly1,int[] poly2){  
  29.  int[] result ;  
  30.  int  n1 =poly1[0] , n2 = poly2[0] ;  
  31.  if(poly1.length > poly2.length){//判斷a1,a2誰比較長  
  32.   result = new int[poly1.length];  
  33.   result[0] = poly1[0];  
  34.  }  
  35.  else{  
  36.   result = new int[poly2.length];  
  37.   result[0] = poly2[0];  
  38.  }  
  39.  int j =1 , k = 1 ;  
  40.  for(int i = 1 ; i < result.length; i++){  
  41.   if(n1 == n2 ){//判斷是否同項次  
  42.   result[i] = poly1[j++] + poly2[k++] ;//陣列推進下一個  
  43.   n1-- ; n2 --;//n-1項次  
  44.   }else if(n1 > n2){  
  45.   result[i] = poly1[j++] ;  
  46.   k = i ; //把目前的i位置給 k  
  47.   n1--;  
  48.   }else{  
  49.   result[i] = poly2[k++] ;  
  50.   j = i ;   
  51.   n2-- ;  
  52.   }  
  53.  }  
  54.  printPoly(result,"result");  
  55. }  
  56. }  

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。