feat(c++): binomial expansion

-
This commit is contained in:
newt 2024-10-09 18:02:43 +01:00
parent 7d4d0f47ee
commit 530d674933
2 changed files with 73 additions and 0 deletions

View file

@ -10,3 +10,4 @@ add_executable(pascal code/pascal.cc)
add_executable(babylonian code/babylonian.cc) add_executable(babylonian code/babylonian.cc)
add_executable(karatsuba code/karatsuba.cc) add_executable(karatsuba code/karatsuba.cc)
add_executable(dice code/dice.cc) add_executable(dice code/dice.cc)
add_executable(binomialExpansion code/binomialExpansion.cc)

View file

@ -0,0 +1,72 @@
#include <iostream>
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);
}