Gotta love factorials

This is a method in Java that returns the factorial of the Integer n :

public Double factorial(Integer n){
    if(n == 0) return 1;
    Integer c = n;
    while(c>1){
        c--;
        n *= c;
    }
    return n;
}

This is pretty big. We may want to reduce the number of lines. What's the minimum number of lines you can write this method's body , without changing its signature and returning exactly the same result?

4 2 1 3

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

João Arruda
Apr 18, 2016

Using recursion and ternary operands we can reduce the body to 1 \boxed{1} line:

public Double factorial(Integer n){
    return (n <= 1) ? 1 : n * factorial(n--);
}

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...