Skip to content

Commit 8f06302

Browse files
committed
Factorials of large numbers
1 parent 3667a5e commit 8f06302

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

DSA Crack Sheet/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
- [Common elements](https://practice.geeksforgeeks.org/problems/common-elements1132/1# "view question") - [Cpp Solution](./solutions/Common%20elements.cpp)
2323
- [Rearrange array in alternating positive & negative items with O(1) extra space](https://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/ "view topic") - [Cpp Solution](./solutions/Rearrange%20array%20in%20alternating%20positive%20&%20negative%20items%20with%20O(1)%20extra%20space.cpp)
2424
- [Subarray with 0 sum](https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1# "view question") - [Cpp Solution](./solutions/Subarray%20with%200%20sum.cpp)
25+
- [Factorials of large numbers](https://practice.geeksforgeeks.org/problems/factorials-of-large-numbers/0# "view question") - [Cpp Solution](./solutions/Factorials%20of%20large%20numbers.cpp)
2526
- []( "view question") - [Cpp Solution](./solutions/.cpp)
2627

2728
<!-- - []( "view question") - [Cpp Solution](./solutions/) -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
Factorials of large numbers
3+
===========================
4+
5+
Given an integer, the task is to find factorial of the number.
6+
7+
Input:
8+
The first line of input contains an integer T denoting the number of test cases.
9+
The first line of each test case is N,the number whose factorial is to be found
10+
11+
Output:
12+
Print the factorial of the number in separate line.
13+
14+
Constraints:
15+
1 ≤ T ≤ 100
16+
1 ≤ N ≤ 1000
17+
18+
Example:
19+
Input:
20+
3
21+
5
22+
10
23+
2
24+
25+
Output:
26+
120
27+
3628800
28+
2
29+
*/
30+
31+
#include <bits/stdc++.h>
32+
using namespace std;
33+
34+
int main()
35+
{
36+
int t;
37+
cin >> t;
38+
while (t--)
39+
{
40+
int n;
41+
cin >> n;
42+
string ans = "1";
43+
for (int i = 2; i <= n; ++i)
44+
{
45+
int carry = 0;
46+
for (auto &ch : ans)
47+
{
48+
int num = ch - '0';
49+
num = i * num;
50+
num += carry;
51+
int digit = num % 10;
52+
ch = (digit + '0');
53+
carry = num / 10;
54+
}
55+
56+
while (carry)
57+
{
58+
int digit = carry % 10;
59+
carry = carry / 10;
60+
ans += to_string(digit);
61+
}
62+
}
63+
64+
reverse(ans.begin(), ans.end());
65+
cout << ans << endl;
66+
}
67+
return 0;
68+
}

0 commit comments

Comments
 (0)