Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions solutions/cpp/complex-numbers/1/complex_numbers.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#include "complex_numbers.h"
#include <cmath>

using namespace std;

namespace complex_numbers {

Complex::Complex(double real, double imag) : m_real(real), m_imag(imag) {}

double Complex::real() const { return m_real; }
double Complex::imag() const { return m_imag; }

double Complex::abs() const {
return sqrt((m_real * m_real) + (m_imag * m_imag));
}

Complex Complex::conj() const {
return Complex(m_real, -m_imag);
}

Complex Complex::exp() const {
double exp_real = std::exp(m_real);
return Complex(exp_real * cos(m_imag), exp_real * sin(m_imag));
}

Complex operator+(const Complex& lhs, const Complex& rhs) {
return Complex(lhs.m_real + rhs.m_real, lhs.m_imag + rhs.m_imag);
}

Complex operator-(const Complex& lhs, const Complex& rhs) {
return Complex(lhs.m_real - rhs.m_real, lhs.m_imag - rhs.m_imag);
}

Complex operator*(const Complex& lhs, const Complex& rhs) {
double r = (lhs.m_real * rhs.m_real) - (lhs.m_imag * rhs.m_imag);
double i = (lhs.m_imag * rhs.m_real) + (lhs.m_real * rhs.m_imag);
return Complex(r, i);
}

Complex operator/(const Complex& lhs, const Complex& rhs) {
double denominator = (rhs.m_real * rhs.m_real) + (rhs.m_imag * rhs.m_imag);

double r = ((lhs.m_real * rhs.m_real) + (lhs.m_imag * rhs.m_imag)) / denominator;
double i = ((lhs.m_imag * rhs.m_real) - (lhs.m_real * rhs.m_imag)) / denominator;

return Complex(r, i);
}

}
30 changes: 30 additions & 0 deletions solutions/cpp/complex-numbers/1/complex_numbers.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#pragma once

namespace complex_numbers {

class Complex {
private:
double m_real;
double m_imag;

public:
// Constructor
Complex(double real = 0.0, double imag = 0.0);

// Getters
double real() const;
double imag() const;

// Métodos unarios
double abs() const;
Complex conj() const;
Complex exp() const;

// Operadores Simétricos como funciones libres "friend"
friend Complex operator+(const Complex& lhs, const Complex& rhs);
friend Complex operator-(const Complex& lhs, const Complex& rhs);
friend Complex operator*(const Complex& lhs, const Complex& rhs);
friend Complex operator/(const Complex& lhs, const Complex& rhs);
};

}