From 530d674933c81dffec97e504634428a94400084e Mon Sep 17 00:00:00 2001 From: newt Date: Wed, 9 Oct 2024 18:02:43 +0100 Subject: [PATCH] feat(c++): binomial expansion - --- languages/c++/CMakeLists.txt | 1 + languages/c++/code/binomialExpansion.cc | 72 +++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 languages/c++/code/binomialExpansion.cc diff --git a/languages/c++/CMakeLists.txt b/languages/c++/CMakeLists.txt index 9d2e238..c33e248 100644 --- a/languages/c++/CMakeLists.txt +++ b/languages/c++/CMakeLists.txt @@ -10,3 +10,4 @@ add_executable(pascal code/pascal.cc) add_executable(babylonian code/babylonian.cc) add_executable(karatsuba code/karatsuba.cc) add_executable(dice code/dice.cc) +add_executable(binomialExpansion code/binomialExpansion.cc) diff --git a/languages/c++/code/binomialExpansion.cc b/languages/c++/code/binomialExpansion.cc new file mode 100644 index 0000000..c474921 --- /dev/null +++ b/languages/c++/code/binomialExpansion.cc @@ -0,0 +1,72 @@ +#include + +std::string superscript[10] = {"⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"}; + +int factorial(int number) { + int out = 1; + + for (int i = 2; i <= number; i++) { + out *= i; + } + + return out; +} + +int nCr(int n, int r) { + return factorial(n) / (factorial(r) * factorial(n - r)); +} + +std::string formatNomial(int value, std::string nomial) { + std::string term = nomial; + + if (value != 1) { + std::string power = ""; + + for (char & digit : std::to_string(value)) { + power += superscript[digit - '0']; + } + + term += power; + } + + return term; +} + +std::string binomialExpansion(int power) { + std::string output = ""; + + for (int r = 0; r <= power; r++) { + int a = power - r; + int c = nCr(power, r); + std::string term = ""; + + if (c != 1) { + term += std::to_string(c); + } + + if (a != 0) { + term += formatNomial(a, "a"); + } + + if (r != 0) { + term += formatNomial(r, "b"); + } + + if (r != 0) { + output += " + " + term; + } else { + output += term; + } + } + + return output; +} + +int main() { + std::cout << "(a + b)ⁿ\nPlease input a value for n! "; + + int n; + std::cin >> n; + + std::cout << binomialExpansion(n); +}