Skip to content

Instantly share code, notes, and snippets.

@patelpreet422
Last active June 9, 2018 19:31
Show Gist options
  • Save patelpreet422/609e4e2f2c733e4ec0596134a6a2e771 to your computer and use it in GitHub Desktop.
Save patelpreet422/609e4e2f2c733e4ec0596134a6a2e771 to your computer and use it in GitHub Desktop.
Factorial of large numbers
#include <iostream>
#include <algorithm>
#include <string>
#include <chrono>
using namespace std::chrono;
const int limit = 200;
const std::string factorial(int n)
{
std::string res(limit, '0');
res[0] = '1';
for (int j = 1; j <= n; ++j)
{
int carry = 0;
for (int i = 0; i < limit; ++i)
{
int product = (res[i] - '0')*j + carry;
res[i] = '0' + (product % 10);
carry = product / 10;
}
}
std::reverse(res.begin(), res.end());
res.erase(0, res.find_first_not_of('0'));
return res;
}
int main()
{
int n = 100;
auto begin = system_clock::now();
std::string f = factorial(n);
std::cout << f << '\n';
auto end = system_clock::now();
auto elapsed = duration_cast<milliseconds>(end - begin);
std::cout << "Time elapsed: " << elapsed.count() << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment