Lately, I've been working on the Euler projects. I just started coding in C++ and could really use some feedback. Basically, I wrote a program to calculate the factorial of any number between 1 and 100 (I have not tested it above 100).
I looked into the Boost library, but it seemed a little bit to easy, so I wrote some algorithms on my own.
Anyway, I would really like some comments about whether this is efficient or not, and if I can somehow optimize the algorithms? I hope this post is within the scope of the forum, since it is my first.
I first convert two integers to vectors, storing each digit separately:
// Converting number to vector
std::vector<int> LargeNumber(int number) {
std::vector<int> numbers;
while (number > 0) {
numbers.push_back(number % 10);
number /= 10;
}
return numbers;
}
Then I pass the vectors on to one of these two functions, depending on whether I want to add or multiply:
// Adds large numbers
std::vector<int> addition(std::vector<int> max, std::vector<int> min) {
if (max.size() < min.size()) {
max.swap(min);
}
std::vector<int> sum;
int rest = 0;
for (int i = 0; i < min.size(); i++) {
int c = min[i] + max[i] + rest;
sum.push_back(c % 10);
rest = c / 10;
}
for (int i = min.size(); i < max.size(); i++) {
int c = max[i] + rest;
sum.push_back(c % 10);
rest = c / 10;
}
while (rest > 0) {
sum.push_back(rest % 10);
rest /= 10;
}
return sum;
}
// Multiplying large numbers
std::vector<int> multiplication(std::vector<int> max, std::vector<int> min) {
if (max.size() < min.size()) {
max.swap(min);
}
std::vector<std::vector<int>> sums;
std::vector<int> sum;
for (int i = 0; i < min.size(); i++) {
sum.resize(0);
int n = i;
while (n > 0) {
sum.push_back(0);
n--;
}
int rest = 0;
for (int j = 0; j < max.size(); j++) {
int c = max[j] * min[i] + rest;
sum.push_back(c % 10);
rest = c / 10;
}
while (rest > 0) {
sum.push_back(rest % 10);
rest /= 10;
}
sums.push_back(sum);
}
sum.resize(0);
for (int i = 0; i < sums.size(); i++) {
sum = addition(sum, sums[i]);
}
return sum;
}
I can then calculate the factorial as:
#include <vector>
int main () {
// Calculating the factorial of the number N
int N = 100;
std::vector<int> fac;
sum.push_back(1);
for (int i = 2; i <= N; i++) {
fac = multiplication(sum, LargeNumber(i));
}
// Printing the result
std::cout << "The factorial of " << N << ": " << std::endl;
for (int i = sum.size()-1; i >= 0; i--) {
std::cout << fac[i];
} std::cout << std::endl;
}
Since I am very new to C++, it is hard for me to know what exactly to ask for, so any comment is very welcome.
LargeNumberwon't work on zero \$\endgroup\$