Skip to content

Factorial

Query Source: adopted from here

Introduction

Factorial is one of most common mathematical concepts, which is the product of all positive integers less than or equal to n. It is denoted mathematically as,

n! = n \times (n-1) \times (n-2) \times \cdot\cdot\cdot \times 1

This is commonly seen in combinations and permutations or Taylor series.

Question

Implement a function factorial to calculate the factorial of a given integer. Return zero if the input integer is negative. Try your best to provide multiple implementations.

Answer

Below are a couple of suggested implementations:

Method 1: Use prd

factorial:{$[x<0;0;prd 1+til x]};

Method 2: Use recursive function

factorial:{$[x<0;0;x=0;1;x*.z.s x-1]};

Method 3: Use over

factorial:{$[x<0;0;(*/)1+til x]};

Method 4: Use do

factorial:{do[-1+current:result:x;result*:current-:1];$[result<0;0;1|result]};