请用Java语言写一个一元稀疏多项式,并且可以输入并建立多项式,多项式a和b相加,建立多项式a+b
时间: 2024-02-25 11:56:55 浏览: 55
基于Java语言实现一元稀疏多项式计算器【100010608】
5星 · 资源好评率100%
好的,以下是示例代码:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class SparsePolynomial {
private ArrayList<Term> terms;
public SparsePolynomial() {
terms = new ArrayList<Term>();
}
public void addTerm(int coefficient, int exponent) {
if (coefficient != 0) {
terms.add(new Term(coefficient, exponent));
}
}
public SparsePolynomial add(SparsePolynomial other) {
SparsePolynomial result = new SparsePolynomial();
int i = 0, j = 0;
while (i < terms.size() && j < other.terms.size()) {
Term term1 = terms.get(i);
Term term2 = other.terms.get(j);
if (term1.exponent == term2.exponent) {
int coefficient = term1.coefficient + term2.coefficient;
result.addTerm(coefficient, term1.exponent);
i++;
j++;
} else if (term1.exponent > term2.exponent) {
result.addTerm(term1.coefficient, term1.exponent);
i++;
} else {
result.addTerm(term2.coefficient, term2.exponent);
j++;
}
}
for (; i < terms.size(); i++) {
result.addTerm(terms.get(i).coefficient, terms.get(i).exponent);
}
for (; j < other.terms.size(); j++) {
result.addTerm(other.terms.get(j).coefficient, other.terms.get(j).exponent);
}
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Collections.sort(terms);
boolean firstTerm = true;
for (Term term : terms) {
if (term.coefficient > 0 && !firstTerm) {
sb.append("+");
}
sb.append(term.coefficient);
if (term.exponent > 1) {
sb.append("x^").append(term.exponent);
} else if (term.exponent == 1) {
sb.append("x");
}
firstTerm = false;
}
return sb.toString();
}
private static class Term implements Comparable<Term> {
private int coefficient;
private int exponent;
public Term(int coefficient, int exponent) {
this.coefficient = coefficient;
this.exponent = exponent;
}
@Override
public int compareTo(Term other) {
return other.exponent - exponent;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
SparsePolynomial a = new SparsePolynomial();
SparsePolynomial b = new SparsePolynomial();
System.out.println("请输入多项式a的项数:");
int na = scanner.nextInt();
for (int i = 0; i < na; i++) {
System.out.println("请输入a的第" + (i+1) + "项的系数和指数:");
int coefficient = scanner.nextInt();
int exponent = scanner.nextInt();
a.addTerm(coefficient, exponent);
}
System.out.println("请输入多项式b的项数:");
int nb = scanner.nextInt();
for (int i = 0; i < nb; i++) {
System.out.println("请输入b的第" + (i+1) + "项的系数和指数:");
int coefficient = scanner.nextInt();
int exponent = scanner.nextInt();
b.addTerm(coefficient, exponent);
}
SparsePolynomial c = a.add(b);
System.out.println("多项式a为:" + a);
System.out.println("多项式b为:" + b);
System.out.println("多项式a+b为:" + c);
}
}
```
运行程序后,会要求依次输入多项式a和b的项数,然后输入每一项的系数和指数。程序会根据输入的多项式建立SparsePolynomial对象,并调用add方法计算a+b,最后输出结果。
阅读全文