The Double Factorial

Difficulty: ★ ★ ☆ ☆

It’s common in programming to use a factorial as a way to teach about recursion. For example, 5! (five factorial) is 5×4×3×2×1, which is 120. Calculating this result can be done with a recursive function, which is practical and satisfying. But mathematicians have a twisted sense of humor, so they invented something called a double factorial.

A double factorial works like a factorial, but the results are based on parity of the original value, odd or even. The calculation still involves descending values, just not all of them.

For example: 5!! (five double-factorial) is equal to 5×3×1, which is 15. Because five is an odd number, only odd values are used to calculate the result. Values 4 and 2 are skipped.

Here’s an even parity double factorial calculation:

8!! = 8×6×4×2 = 384

Only even values are used to obtain the result. Values 7, 5, and 3 are skipped. (Obviously, the final value, one, has no impact on the result.)

When I first encountered the double factorial, I was surprised that the results are less than a single factorial; “double” implies larger, right? Yet, this relationship means that n! > n!!. I’m uncertain what bearing this effect has, though it’s interesting to note that mathematically n! = n!! * (n-1)!!

For example: 5! = 120. The result of 5!! is 15 and the result of 4!! = 8. Multiply the results together, 15×8, and you get 120, which is 5!.

Enough math!

Your task for this month’s Exercise is to write code that calculates the double factorial of a positive integer. Prompt the use to input a positive integer value. Output the result.

Here’s a sample run from my solution:

Enter a positive integer: 9
9!! = 945

To confirm your result, you can visit the Calculator Soup website, which features a double factorial calculator.

Please try this challenge on your own before you sneak a look at my solutions. One uses a loop and the other uses recursion to calculate the double factorial.

Leave a Reply