TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
double_factorial.cpp
Go to the documentation of this file.
1
12#include <cassert>
13#include <cstdint>
14#include <iostream>
15
18uint64_t double_factorial_iterative(uint64_t n) {
19 uint64_t res = 1;
20 for (uint64_t i = n;; i -= 2) {
21 if (i == 0 || i == 1)
22 return res;
23 res *= i;
24 }
25 return res;
26}
27
31uint64_t double_factorial_recursive(uint64_t n) {
32 if (n <= 1)
33 return 1;
34 return n * double_factorial_recursive(n - 2);
35}
36
43void test(uint64_t n, uint64_t expected) {
44 assert(double_factorial_iterative(n) == expected);
45 assert(double_factorial_recursive(n) == expected);
46}
47
51void tests() {
52 std::cout << "Test 1:\t n=5\t...";
53 test(5, 15);
54 std::cout << "passed\n";
55
56 std::cout << "Test 2:\t n=15\t...";
57 test(15, 2027025);
58 std::cout << "passed\n";
59
60 std::cout << "Test 3:\t n=0\t...";
61 test(0, 1);
62 std::cout << "passed\n";
63}
64
68int main() {
69 tests();
70 return 0;
71}
uint64_t double_factorial_iterative(uint64_t n)
uint64_t double_factorial_recursive(uint64_t n)
void tests()
int main()
static void test()
Self-test implementations.