Still looking for a sponsor Max Paulousky is looking for a Silverlight/.Net job in the Commonwealth

Share to Facebook Tweet this! Share to MySpace Share to Google Share to Live   Share via AddThis

Single-Line Solution: Factorial

Recently my colleagues started a dispute whether it is possible to calculate a factorial using just one line of code.

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. (by Wikipedia)

One line means a line that ends with a semicolon:


Of course, following sample is not the single-row code:

for(;;;) bla-bla-bla;

First idea is using recursion (let’s arrange, it is the single-line code):

Func<int, int> factorial = n => n < 2 ? 1 : n * factorial(n - 1);
int result = factorial(10);
but it does not work (the factorial expression is not defined before evaluating the right side of the assignment).   

Following variant works but it is not the single-row solution (at least two code lines – factorial defining and initializing):

Func<int, int> factorial = null; 
factorial = n => n < 2 ? 1 : n * factorial(n - 1);
int result = factorial(10);

The simplest variant of the single-line factorial calculating is

int factorial = Enumerable.Range(1, n).Aggregate((accumulator, next) => accumulator * next);

The aggregate function takes the first element of the enumeration and put it into accumulator. Then it multiplies accumulator and next and put the result into accumulator again. Aggregate repeats the action for all elements. The result looks like

(....((((1 * 2) * 3) * 4) * 5) * .......) * n

Next single-line solution I want to implement is a Fibonacci calculator.

This work is licensed under a Creative Commons Attribution By license.
Comments have been closed on this topic.