Java 一元多项式的乘法与加法运算
2020-03-30 本文已影响0人
向祥祥
问题
求两个一元多项式的乘积与和。
输入格式:输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数。数字间以空格分隔。
输出格式:输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。相乘或相加结果为0,则输出:0 0。
输入示例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出示例:
15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0
计算代码
public static void main(String[] args) {
TreeMap<Integer,Integer> polynomial1=new TreeMap<Integer, Integer>();
TreeMap<Integer,Integer> afterSummation=new TreeMap<Integer, Integer>();
TreeMap<Integer,Integer> afterMultiplication=new TreeMap<Integer, Integer>();
Scanner sc=new Scanner(System.in);
int index=sc.nextInt();
for(int i=1;i<=index;i++) {
int coefficient=sc.nextInt();
int indices=sc.nextInt();
polynomial1.put(indices, coefficient);
afterSummation.put(indices, coefficient);
}
index=sc.nextInt();
for(int i=1;i<=index;i++) {
int coefficient=sc.nextInt();
int indices=sc.nextInt();
polynomialSummationOnePolynomial(afterSummation,indices,coefficient);
polynomialSummationMultiplePolynomial(afterMultiplication,polynomialMultiplicationOne(polynomial1,indices,coefficient));
}
sc.close();
System.out.println(printHashMap(afterMultiplication));
System.out.println(printHashMap(afterSummation));
}
public static String printHashMap(TreeMap<Integer,Integer> needPrint) {
String str="";
for(Entry<Integer,Integer> entry:needPrint.entrySet()) {
if(entry.getValue()!=0) {
str=" "+entry.getValue()+" "+entry.getKey()+str;
}
}
if(str.equals("")) {
str="0 0";
}
return str.trim();
}
public static TreeMap<Integer,Integer> polynomialMultiplicationOne(TreeMap<Integer,Integer> needMultiplication,int indices,int coefficient){
TreeMap<Integer,Integer> afterMultiplication=new TreeMap<Integer, Integer>();
for(Entry<Integer, Integer> entry:needMultiplication.entrySet()) {
afterMultiplication.put(entry.getKey()+indices, entry.getValue()*coefficient);
}
return afterMultiplication;
}
public static void polynomialSummationMultiplePolynomial(TreeMap<Integer,Integer> afterSummation,TreeMap<Integer,Integer> needSummation){
for(Entry<Integer, Integer> entry:needSummation.entrySet()) {
if(afterSummation.containsKey(entry.getKey())) {
afterSummation.put(entry.getKey(), afterSummation.get(entry.getKey())+entry.getValue());
}else {
afterSummation.put(entry.getKey(), entry.getValue());
}
}
}
public static void polynomialSummationOnePolynomial(TreeMap<Integer,Integer> afterSummation,int indices,int coefficient){
if(afterSummation.containsKey(indices)) {
afterSummation.put(indices, afterSummation.get(indices)+coefficient);
}else{
afterSummation.put(indices, coefficient);
}
}