728x90
public class Polynomial {
int degree;
long[] coefficients;
// Constructor
public Polynomial(int deg) {
this.degree = deg;
this.coefficients = new long[deg + 1];
for (int i = 0; i < deg + 1; i++) {
this.coefficients[i] = 0;
}
}
public static Polynomial copy(Polynomial source) {
Polynomial newPoly = new Polynomial(source.degree);
for (int i = 0; i <= source.degree; i++) {
newPoly.coefficients[i] = source.coefficients[i];
}
return newPoly;
}
public void displayPolynomial(Polynomial source) {
for (int i = source.degree; i >= 0; i--) {
System.out.print(source.coefficients[i] + "x^" + i);
if (i > 0) {
System.out.print(" + ");
}
}
System.out.println();
}
public static boolean equalTo(Polynomial P, Polynomial Q) {
if (P.degree != Q.degree) {
return false;
}
for (int i = 0; i <= P.degree; i++) {
if (P.coefficients[i] != Q.coefficients[i]) {
return false;
}
}
return true;
}
public static long evaluate(Polynomial source, long x) {
long result = 0;
for (int i = 0; i <= source.degree; i++) {
result += source.coefficients[i] * Math.pow(x, i);
}
return result;
}
public static Polynomial derivative(Polynomial source) {
if (source.degree == 0) {
return new Polynomial(0); // Derivative of a constant is 0
}
Polynomial derivative = new Polynomial(source.degree - 1);
for (int i = 1; i <= source.degree; i++) {
derivative.coefficients[i - 1] = source.coefficients[i] * i;
}
return derivative;
}
public static Polynomial add(Polynomial P, Polynomial Q) {
int maxDegree = Math.max(P.degree, Q.degree);
Polynomial result = new Polynomial(maxDegree);
for (int i = 0; i <= maxDegree; i++) {
long pCoeff = (i <= P.degree) ? P.coefficients[i] : 0;
long qCoeff = (i <= Q.degree) ? Q.coefficients[i] : 0;
result.coefficients[i] = pCoeff + qCoeff;
}
return result;
}
public static Polynomial subtract(Polynomial P, Polynomial Q) {
int maxDegree = Math.max(P.degree, Q.degree);
Polynomial result = new Polynomial(maxDegree);
for (int i = 0; i <= maxDegree; i++) {
long pCoeff = (i <= P.degree) ? P.coefficients[i] : 0;
long qCoeff = (i <= Q.degree) ? Q.coefficients[i] : 0;
result.coefficients[i] = pCoeff - qCoeff;
}
return result;
}
public static long HornerScheme(Polynomial source, long x) {
long result = 0;
for (int i = source.degree; i >= 0; i--) {
result = result * x + source.coefficients[i];
}
return result;
}
}
728x90
'호그와트' 카테고리의 다른 글
사과 팝니다 한 입 하세요~~ (0) | 2024.05.02 |
---|---|
어느새 Java가 나의 모국어가 되었다 (0) | 2024.01.24 |
내가 밖에서 시로 봤는데 흠흐밍 흠흐밍 하면서 돌아다니더라 (0) | 2023.12.08 |
panda's attack (0) | 2023.11.17 |
TwoArray.java (0) | 2023.11.14 |