数据结构一元多项式运算器Java
时间: 2024-04-17 13:21:00 浏览: 202
数据结构是计算机科学中研究数据组织、存储和管理的一门学科。一元多项式是数学中的概念,它由一个变量和对应的系数构成。一元多项式运算器是一个能够对一元多项式进行各种运算的程序或工具。
在Java中实现一元多项式运算器,可以使用链表或数组等数据结构来表示和存储多项式。以下是一个简单的示例代码:
```java
import java.util.*;
class Term {
int coefficient;
int exponent;
public Term(int coefficient, int exponent) {
this.coefficient = coefficient;
this.exponent = exponent;
}
}
class Polynomial {
List<Term> terms;
public Polynomial() {
terms = new ArrayList<>();
}
public void addTerm(int coefficient, int exponent) {
terms.add(new Term(coefficient, exponent));
}
public Polynomial add(Polynomial other) {
Polynomial result = new Polynomial();
result.terms.addAll(this.terms);
for (Term term : other.terms) {
boolean found = false;
for (Term existingTerm : result.terms) {
if (existingTerm.exponent == term.exponent) {
existingTerm.coefficient += term.coefficient;
found = true;
break;
}
}
if (!found) {
result.terms.add(term);
}
}
return result;
}
public Polynomial multiply(Polynomial other) {
Polynomial result = new Polynomial();
for (Term term1 : this.terms) {
for (Term term2 : other.terms) {
int coefficient = term1.coefficient * term2.coefficient;
int exponent = term1.exponent + term2.exponent;
result.addTerm(coefficient, exponent);
}
}
return result;
}
public void print() {
for (Term term : terms) {
System.out.print(term.coefficient + "x^" + term.exponent + " + ");
}
System.out.println();
}
}
public class PolynomialCalculator {
public static void main(String[] args) {
Polynomial p1 = new Polynomial();
p1.addTerm(2, 3);
p1.addTerm(4, 2);
p1.addTerm(1, 0);
Polynomial p2 = new Polynomial();
p2.addTerm(3, 2);
p2.addTerm(1, 1);
p2.addTerm(5, 0);
Polynomial sum = p1.add(p2);
Polynomial product = p1.multiply(p2);
System.out.println("Sum:");
sum.print();
System.out.println("Product:");
product.print();
}
}
```
这个示例代码实现了一个简单的一元多项式运算器,可以进行多项式的加法和乘法运算。你可以根据需要扩展该代码,添加其他运算功能。
阅读全文