TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
large_factorial.cpp
Go to the documentation of this file.
1
8#include <cstring>
9#include <ctime>
10#include <iostream>
11
12#include "./large_number.h"
13
17bool test1() {
18 std::cout << "---- Check 1\t";
19 unsigned int i, number = 10;
20 large_number result;
21 for (i = 2; i <= number; i++) /* Multiply every number from 2 thru N */
22 result *= i;
23
24 const char *known_reslt = "3628800";
25
26 /* check 1 */
27 if (strlen(known_reslt) != result.num_digits()) {
28 std::cerr << "Result lengths dont match! " << strlen(known_reslt)
29 << " != " << result.num_digits() << std::endl;
30 return false;
31 }
32
33 const size_t N = result.num_digits();
34 for (i = 0; i < N; i++) {
35 if (known_reslt[i] != result.digit_char(i)) {
36 std::cerr << i << "^th digit mismatch! " << known_reslt[i]
37 << " != " << result.digit_char(i) << std::endl;
38 return false;
39 }
40 }
41
42 std::cout << "Passed!" << std::endl;
43 return true;
44}
45
54bool test2() {
55 std::cout << "---- Check 2\t";
56 unsigned int i, number = 100;
57 large_number result;
58 for (i = 2; i <= number; i++) /* Multiply every number from 2 thru N */
59 result *= i;
60
61 const char *known_reslt =
62 "9332621544394415268169923885626670049071596826438162146859296389521759"
63 "9993229915608941463976156518286253697920827223758251185210916864000000"
64 "000000000000000000";
65
66 /* check 1 */
67 if (strlen(known_reslt) != result.num_digits()) {
68 std::cerr << "Result lengths dont match! " << strlen(known_reslt)
69 << " != " << result.num_digits() << std::endl;
70 return false;
71 }
72
73 const size_t N = result.num_digits();
74 for (i = 0; i < N; i++) {
75 if (known_reslt[i] != result.digit_char(i)) {
76 std::cerr << i << "^th digit mismatch! " << known_reslt[i]
77 << " != " << result.digit_char(i) << std::endl;
78 return false;
79 }
80 }
81
82 std::cout << "Passed!" << std::endl;
83 return true;
84}
85
89int main(int argc, char *argv[]) {
90 int number, i;
91
92 if (argc == 2) {
93 number = atoi(argv[1]);
94 } else {
95 std::cout << "Enter the value of n(n starts from 0 ): ";
96 std::cin >> number;
97 }
98
99 large_number result;
100
101 std::clock_t start_time = std::clock();
102 for (i = 2; i <= number; i++) /* Multiply every number from 2 thru N */
103 result *= i;
104 std::clock_t end_time = std::clock();
105 double time_taken =
106 static_cast<double>(end_time - start_time) / CLOCKS_PER_SEC;
107
108 std::cout << number << "! = " << result << std::endl
109 << "Number of digits: " << result.num_digits() << std::endl
110 << "Time taken: " << std::scientific << time_taken << " s"
111 << std::endl;
112
113 test1();
114 test2();
115 result.test();
116
117 return 0;
118}
int main()
Main function.
bool test1()
bool test2()
Library to perform arithmatic operations on arbitrarily large numbers.