Algorithms_in_C++ 1.0.0
Set of 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:

Namespaces

namespace  math
 for IO operations
 

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\)

Function Documentation

◆ main()

int main ( void )

Main function.

Returns
0 on exit
118 {
119 test(); // Run self-test implementation
120 return 0;
121}
static void test()
Self-test implementations to test iterativeFactorial function.
Definition iterative_factorial.cpp:69
Here is the call graph for this function:

◆ test()

static void test ( )
static

Self-test implementations to test iterativeFactorial function.

Note
There is 1 special case: 0! = 1.
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 try {
106 } catch (std::invalid_argument* e) {
107 std::cout << "Exception thrown successfully \nContent: " << e->what()
108 << "\n";
109 }
110
111 std::cout << "All tests have passed successfully.\n";
112}
uint64_t iterativeFactorial(uint8_t n)
Calculates the factorial iteratively.
Definition iterative_factorial.cpp:47
Here is the call graph for this function: