TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
iterative_factorial.cpp File Reference

Iterative implementation of Factorial More...

#include <cassert>
#include <cstdint>
#include <exception>
#include <iostream>
Include dependency graph for iterative_factorial.cpp:

Go to the source code of this file.

Namespaces

namespace  math
 for assert
 

Functions

uint64_t math::iterativeFactorial (uint8_t n)
 Calculates the factorial iteratively.
 
static void test ()
 Self-test implementations to test iterativeFactorial function.
 
int main ()
 Main function.
 

Detailed Description

Iterative implementation of Factorial

Author
Renjian-buchai

Calculates factorial iteratively.

\[n! = n\times(n-1)\times(n-2)\times(n-3)\times\ldots\times3\times2\times1 = n\times(n-1)!\]

for example: \(4! = 4\times3! = 4\times3\times2\times1 = 24\)

Definition in file iterative_factorial.cpp.

Function Documentation

◆ main()

int main ( void )

Main function.

Returns
0 on exit

Definition at line 120 of file iterative_factorial.cpp.

120 {
121 test(); // Run self-test implementation
122 return 0;
123}
static void test()
Self-test implementations to test iterativeFactorial function.

◆ test()

static void test ( )
static

Self-test implementations to test iterativeFactorial function.

Note
There is 1 special case: 0! = 1.

Definition at line 69 of file iterative_factorial.cpp.

69 {
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 {
108 } catch (const std::invalid_argument&) {
109 wasExceptionThrown = true;
110 }
111 assert(wasExceptionThrown);
112
113 std::cout << "All tests have passed successfully.\n";
114}
uint64_t iterativeFactorial(uint8_t n)
Calculates the factorial iteratively.