Created
June 30, 2012 04:50
-
-
Save wolfiestyle/3022338 to your computer and use it in GitHub Desktop.
multiplicacion de polinomios en C++ basico
This file contains 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
#include <iostream> | |
#include <algorithm> | |
#include <cassert> | |
enum | |
{ | |
MAX_COEFF = 16, | |
}; | |
struct polinomio | |
{ | |
float m_coeff[MAX_COEFF]; | |
int m_max; | |
polinomio(): | |
m_max(-1) | |
{ | |
std::fill_n(m_coeff, (size_t)MAX_COEFF, 0.f); | |
} | |
void set_coeff(int i, float val) | |
{ | |
assert(i >= 0 && i < MAX_COEFF); | |
m_coeff[i] = val; | |
if (i > m_max) | |
m_max = i; | |
} | |
void print() | |
{ | |
std::cout << std::noshowpos; | |
for (int i = m_max, n = 0; i >= 0; --i) | |
{ | |
if (!m_coeff[i]) | |
continue; | |
if (n++) | |
std::cout << std::showpos; | |
std::cout << m_coeff[i]; | |
if (i) | |
std::cout << 'x'; | |
if (i > 1) | |
std::cout << '^' << std::noshowpos << i; | |
} | |
std::cout << std::endl; | |
} | |
polinomio operator* (polinomio const& rhs) | |
{ | |
polinomio res; | |
res.m_max = m_max + rhs.m_max; | |
assert(res.m_max < MAX_COEFF); | |
for (int i = 0; i <= m_max; ++i) | |
for (int j = 0; j <= rhs.m_max; ++j) | |
res.m_coeff[i + j] += m_coeff[i] * rhs.m_coeff[j]; | |
return res; | |
} | |
}; | |
int main() | |
{ | |
// x^2 + 3x + 5 | |
polinomio p1; | |
p1.set_coeff(2, 1); | |
p1.set_coeff(1, 3); | |
p1.set_coeff(0, 5); | |
p1.print(); | |
// x^2 + 4 | |
polinomio p2; | |
p2.set_coeff(2, 1); | |
p2.set_coeff(0, -1); | |
p2.print(); | |
// multiplicacion | |
polinomio p3 = p1 * p2; | |
p3.print(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment