TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
iterative_factorial.cpp
Go to the documentation of this file.
1
27
28
#include <cassert>
29
#include <cstdint>
30
#include <exception>
31
#include <iostream>
32
37
namespace
math
{
38
47
uint64_t
iterativeFactorial
(uint8_t n) {
48
if
(n > 20) {
49
throw
std::invalid_argument(
"Maximum n value is 20"
);
50
}
51
52
// 1 because it is the identity number of multiplication.
53
uint64_t accumulator = 1;
54
55
while
(n > 1) {
56
accumulator *= n;
57
--n;
58
}
59
60
return
accumulator;
61
}
62
63
}
// namespace math
64
69
static
void
test
() {
70
// Special case test
71
std::cout <<
"Exception case test \n"
72
"Input: 0 \n"
73
"Expected output: 1 \n\n"
;
74
assert(
math::iterativeFactorial
(0) == 1);
75
76
// Base case
77
std::cout <<
"Base case test \n"
78
"Input: 1 \n"
79
"Expected output: 1 \n\n"
;
80
assert(
math::iterativeFactorial
(1) == 1);
81
82
// Small case
83
std::cout <<
"Small number case test \n"
84
"Input: 5 \n"
85
"Expected output: 120 \n\n"
;
86
assert(
math::iterativeFactorial
(5) == 120);
87
88
// Medium case
89
std::cout <<
"Medium number case test \n"
90
"Input: 10 \n"
91
"Expected output: 3628800 \n\n"
;
92
assert(
math::iterativeFactorial
(10) == 3628800);
93
94
// Maximum case
95
std::cout <<
"Maximum case test \n"
96
"Input: 20 \n"
97
"Expected output: 2432902008176640000\n\n"
;
98
assert(
math::iterativeFactorial
(20) == 2432902008176640000);
99
100
// Exception test
101
std::cout <<
"Exception test \n"
102
"Input: 21 \n"
103
"Expected output: Exception thrown \n"
;
104
105
bool
wasExceptionThrown =
false
;
106
try
{
107
math::iterativeFactorial
(21);
108
}
catch
(
const
std::invalid_argument&) {
109
wasExceptionThrown =
true
;
110
}
111
assert(wasExceptionThrown);
112
113
std::cout <<
"All tests have passed successfully.\n"
;
114
}
115
120
int
main
() {
121
test
();
// Run self-test implementation
122
return
0;
123
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
math
for assert
math::iterativeFactorial
uint64_t iterativeFactorial(uint8_t n)
Calculates the factorial iteratively.
Definition
iterative_factorial.cpp:47
math
iterative_factorial.cpp
Generated by
1.18.0