Last active
June 9, 2018 19:31
-
-
Save patelpreet422/609e4e2f2c733e4ec0596134a6a2e771 to your computer and use it in GitHub Desktop.
Factorial of large numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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