Created
February 28, 2017 21:38
-
-
Save anonymous/20788b284a10b3fa4479f44841054164 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Polinomio{ | |
private int[] coeficientes; | |
private int grado; | |
public Polinomio(int g){ | |
if (g < 0) { | |
coeficientes = new int[1]; | |
coeficientes[0] = 0; | |
grado = 0; | |
} else { | |
coeficientes = new int[g + 1]; | |
for(int i = 0; i <= g; i++){ | |
coeficientes[i] = 0; | |
grado = g; | |
} | |
} | |
} | |
public Polinomio(int[] coef, int g){ | |
if (g < 0) { | |
coeficientes = new int[1]; | |
coeficientes[0] = 0; | |
grado = 0; | |
} else { | |
coeficientes = new int[g + 1]; | |
for(int i = 0; i <= g; i++){ | |
coeficientes[i] = coef[i]; | |
grado = g; | |
} | |
} | |
} | |
public int grado() { | |
return this.grado; | |
} | |
// regresa c = a + b | |
public Polinomio suma(Polinomio b) { | |
Polinomio a = this; | |
int grado = Math.max(a.grado, b.grado); | |
Polinomio c = new Polinomio(grado); | |
for (int i = 0; i <= a.grado; i++){ | |
c.coeficientes[i] += a.coeficientes[i]; | |
} | |
for (int i = 0; i <= b.grado; i++){ | |
c.coeficientes[i] += b.coeficientes[i]; | |
} | |
return c; | |
} | |
public Polinomio multiplicaEscalar(int escalar){ | |
Polinomio a = this; | |
for(int i = 0; i <= a.grado; i++){ | |
a.coeficientes[i] *= escalar; | |
} | |
return a; | |
} | |
public int evaluar(int x) { | |
int valor = 0; | |
for (int i = this.grado; i >= 0; i--){ | |
valor = this.coeficientes[i] + (x * valor); | |
} | |
return valor; | |
} | |
public String toString() { | |
if (grado == 0) return "" + coeficientes[0]; | |
if (grado == 1) return coeficientes[1] + "x + " + coeficientes[0]; | |
String s = coeficientes[grado] + "x^" + grado; | |
for (int i = grado-1; i >= 0; i--) { | |
if (coeficientes[i] == 0) continue; | |
else if (coeficientes[i] > 0) s = s + " + " + ( coeficientes[i]); | |
else if (coeficientes[i] < 0) s = s + " - " + (-coeficientes[i]); | |
if (i == 1) s = s + "x"; | |
else if (i > 1) s = s + "x^" + i; | |
} | |
return s; | |
} | |
public static void main(String[] args) { | |
int[] coeficientesP = {1,2,3,4}; | |
int gradoP = 3; | |
Polinomio p = new Polinomio(coeficientesP, gradoP); | |
System.out.println("p(x) = " + p); | |
int[] coeficientesQ = {5, 0, 3}; | |
int gradoQ = 2; | |
Polinomio q = new Polinomio(coeficientesQ, gradoQ); | |
System.out.println("q(x) = " + q); | |
Polinomio r = p.suma(q); | |
System.out.println("p(x) + q(x) = " + r); | |
System.out.println("p(3) = " + p.evaluar(3)); | |
Polinomio s = p.multiplicaEscalar(3); | |
System.out.println("3 * p(x) = " + s); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment