- /*
- * 多項式
- */
- public class Polynomial {
- public static void main(String[] args) {
- int[] a = {4,3,7,0,6,2};//第一種表示法 a[0] :項次 剩下微細數
- printPoly(a,"a1");
- int[] b = {5,-1,-5,2,0,9,4};
- printPoly(b,"b1");
- PolySum(a,b);
- }
- static void printPoly(int[] poly,String name){
- System.out.print(name +": ");
- int max = poly[0] ;//最高項次
- for(int i = 1 ; i < poly.length ; i++){
- if(poly[i] != 0){//假如係數是0
- if(max != 0) System.out.print(poly[i] +"X^"+max+"+");
- else System.out.print(poly[i]); //0項次
- max--;
- }else{
- max--;
- continue ;
- }
- }
- System.out.println();
- }
- static void PolySum(int[] poly1,int[] poly2){
- int[] result ;
- int n1 =poly1[0] , n2 = poly2[0] ;
- if(poly1.length > poly2.length){//判斷a1,a2誰比較長
- result = new int[poly1.length];
- result[0] = poly1[0];
- }
- else{
- result = new int[poly2.length];
- result[0] = poly2[0];
- }
- int j =1 , k = 1 ;
- for(int i = 1 ; i < result.length; i++){
- if(n1 == n2 ){//判斷是否同項次
- result[i] = poly1[j++] + poly2[k++] ;//陣列推進下一個
- n1-- ; n2 --;//n-1項次
- }else if(n1 > n2){
- result[i] = poly1[j++] ;
- k = i ; //把目前的i位置給 k
- n1--;
- }else{
- result[i] = poly2[k++] ;
- j = i ;
- n2-- ;
- }
- }
- printPoly(result,"result");
- }
- }
2017年7月29日 星期六
(Java) 多項式
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言
注意:只有此網誌的成員可以留言。