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

Compute double factorial: \(n!!\). More...

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

Go to the source code of this file.

Functions

uint64_t double_factorial_iterative (uint64_t n)
 
uint64_t double_factorial_recursive (uint64_t n)
 
void test (uint64_t n, uint64_t expected)
 
void tests ()
 
int main ()
 

Detailed Description

Compute double factorial: \(n!!\).

Double factorial of a non-negative integer n, is defined as the product of all the integers from 1 to n that have the same parity (odd or even) as n.
It is also called as semifactorial of a number and is denoted by \(n!!\)

Definition in file double_factorial.cpp.

Function Documentation

◆ double_factorial_iterative()

uint64_t double_factorial_iterative ( uint64_t n)

Compute double factorial using iterative method

Definition at line 18 of file double_factorial.cpp.

18 {
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}

◆ double_factorial_recursive()

uint64_t double_factorial_recursive ( uint64_t n)

Compute double factorial using resursive method.
Recursion can be costly for large numbers.

Definition at line 31 of file double_factorial.cpp.

31 {
32 if (n <= 1)
33 return 1;
34 return n * double_factorial_recursive(n - 2);
35}
uint64_t double_factorial_recursive(uint64_t n)

◆ main()

int main ( void )

Main function

Definition at line 68 of file double_factorial.cpp.

68 {
69 tests();
70 return 0;
71}
void tests()

◆ test()

void test ( uint64_t n,
uint64_t expected )

Wrapper to run tests using both recursive and iterative implementations. The checks are only valid in debug builds due to the use of assert() statements.

Parameters
[in]nnumber to check double factorial for
[in]expectedexpected result

Definition at line 43 of file double_factorial.cpp.

43 {
44 assert(double_factorial_iterative(n) == expected);
45 assert(double_factorial_recursive(n) == expected);
46}
uint64_t double_factorial_iterative(uint64_t n)

◆ tests()

void tests ( )

Test implementations

Definition at line 51 of file double_factorial.cpp.

51 {
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}
static void test()
Self-test implementations.