Search code examples
mathlanguage-agnosticfactorial

Writing a factorial() function without distinction between 0 and other numbers


This question has been bugging me for quite a while: is it possible to write a factorial function (in any programming language) without any if statement (or similar) which returns 1 when called with 0 as argument too?

Many factorial functions are something like this (Python):

def factorial(n):
    for x in range(1, n):
        n *= x
    return n if n > 0 else 1

But I don't know if it can be done without distinction between varied values of n... What do you think? It is not a matter of speed and optimizing, just my curiosity.


Solution

  • 0! is defined as 1.

    Here are the results from my code.

    0 factorial = 1
    1 factorial = 1
    2 factorial = 2
    3 factorial = 6
    10 factorial = 3628800
    

    And here's Java code with no if statement,

    package com.ggl.testing;
    
    public class Factorial {
    
        public static void main(String[] args) {
            int n = 0;
            System.out.println(n + " factorial = " + factorial(n));
            n = 1;
            System.out.println(n + " factorial = " + factorial(n));
            n = 2;
            System.out.println(n + " factorial = " + factorial(n));
            n = 3;
            System.out.println(n + " factorial = " + factorial(n));
            n = 10;
            System.out.println(n + " factorial = " + factorial(n));
        }
    
        public static long factorial(int n) {
            long product = 1L;
    
            for (int i = 2; i <= n; i++) {
                product *= (long) i;
            }
    
            return product;
        }
    
    }