Double factorial

2

Double factorial of a non-negative integer n, is 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 !!. For example, double factorial of 9 is 9*7*5*3*1 which is 945. Note that, a consequence of this definition is 0!! = 1.

Examples:

Input: 6
Output: 48
Note that 6*4*2 = 48

Input: 7
Output: 105
Note that 7*5*3 = 105

For even n, the double factorial is:

For odd n, the double factorial is:

Recursive Solution:
Double factorial can be calculated using following recursive formula.

  n!! = n * (n-2)!!
  n!! = 1 if n = 0 or n = 1 

Following is C implementation of double factorial.

#include<stdio.h>
 
// function to find double factorial of given number
unsigned int doublefactorial(unsigned int n)
{
    if (n == 0 || n==1)
      return 1;
    return n*doublefactorial(n-2);
}
 
int main()
{
    printf("Double factorial is %d", doublefactorial(5));
    return 0;
}

Output:

Double factorial is 15

Iterative Solution:
Double factorial can also be calculated iteratively as recursion can be costly for large numbers.

#include<stdio.h>
 
// function to find double factorial of given number
unsigned int doublefactorial(unsigned int n)
{
    int res = 1;
    for (int i=n; i>=0; i=i-2)
    {
        if (i==0 || i==1)
            return res;
        else
            res *= i;
    }
}
 
int main()
{
    printf("Double factorial is %d", doublefactorial(5));
    return 0;
}

Output:

Double factorial is 15

Time complexity of the above solutions is O(n).

Important Points :

  1. Double factorial and factorial are related using below formula.

    Note : n!! means double factorial.
    If n is even, i.e., n = 2k
       n!! = 2kk!
    Else (n = 2k + 1)
       n!! = (2k)! / 2kk! 
    
  2. Double factorial is frequently used in combinatorics. Refer wiki for list of applications. An example application is count of perfect matchings of a complete graph Kn+1 for odd n.

References:
https://en.wikipedia.org/wiki/Double_factorial

This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2 Average Difficulty : 2/5.0
Based on 1 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.