多項式加法如何工作?
答案: - 通過添加相同的功率的係數
SO P1 = 5X^3 - 4X + 8
和P2 = 6X^5 -2X^2 + 7X^1 + -4
變得
P1 = 0X^5 + 5X^3 + 0X^2 - 4X^1 + 8X^0
P2 = 6X^5 + 0X^3 -2X^2 + 7X^1 - 4X^0
____________________________________
SUM = 6X^5 + 5X^3 -2X^2 + 3X^1 + 4X^0
____________________________________
您可以將電源作爲重點和係數的值在Map.Then迭代的地圖,並添加係數的值
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
class SumOfPolynomials {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
List<Map<Integer, Integer>> listOfPolynomials = new ArrayList<Map<Integer, Integer>>();
File polyfile = new File("polyinput.txt");
Scanner read = new Scanner(polyfile);
while (read.hasNextLine()){
String LINE = read.nextLine();
String[] lineSpillted =LINE.split(";");
Map<Integer, Integer> poynomial = new HashMap<Integer, Integer>();
for(int i =1;i<lineSpillted.length-1;i=i+2){ //i starts from ignores P1,P2 etc
poynomial.put(Integer.parseInt(lineSpillted[i+1]), Integer.parseInt(lineSpillted[i]));
}
listOfPolynomials.add(poynomial);
}
read.close();
Map<Integer, Integer> result = polynomialSum(listOfPolynomials.get(0), listOfPolynomials.get(1));
if(listOfPolynomials.size()>2){
for(int i=2;i<listOfPolynomials.size()-1;i++){
result = polynomialSum(result,listOfPolynomials.get(i));
}
}
// print out the SUM as VALUEX^KEY
System.out.println();
int c = 0;
for (Map.Entry<Integer, Integer> entry : result.entrySet()) {
System.out.print(entry.getValue() + "X^" + entry.getKey());
c++;
if (c != result.size()) {
System.out.print("+");
}
}
}
public static Map<Integer, Integer> polynomialSum(Map<Integer, Integer> arg1,
Map<Integer, Integer> arg2) {
Map<Integer, Integer> SUM = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : arg1.entrySet()) {
Integer power = entry.getKey();
Integer coeff1 = entry.getValue();
Integer coefficient;
if (arg2.containsKey(power)) {
coefficient = arg2.get(power) + coeff1;
} else {
coefficient = coeff1;
}
SUM.put(power, coefficient);
}
for (Map.Entry<Integer, Integer> entry : arg2.entrySet()) {
if (SUM.containsKey(entry.getKey())) {
continue;
} else {
SUM.put(entry.getKey(), entry.getValue());
}
}
return SUM;
}
}
編輯的多個Polynomials.Multiple多項式在一個列表中加入,然後總和被計算通過遍歷列表
輸出: -
這並不像您想象的那麼容易。如果它是家庭作業,那麼創建自己的類來解析字符串並創建多項式的抽象表示。否則,找一個處理這個的庫。 – 2014-08-30 15:44:24
我已經嘗試將它們轉換成字符串,但之後我很無能。我閱讀了它們,但在分隔它們之後不知道如何使用它們。我怎麼能做一個未定義的變量數學。然後我必須添加或減去所有單獨的數字也許?我只讀過它們並將它們放入數組列表中。 – Dave 2014-08-30 15:45:03
我如何進行表示? – Dave 2014-08-30 15:47:53