Disallow factorial of negative numbers
authorPeter Eisentraut <peter@eisentraut.org>
Thu, 18 Jun 2020 06:41:31 +0000 (08:41 +0200)
committerPeter Eisentraut <peter@eisentraut.org>
Thu, 18 Jun 2020 06:41:31 +0000 (08:41 +0200)
The previous implementation returned 1 for all negative numbers, which
is not sensible under any definition.

Discussion: https://www.postgresql.org/message-id/flat/6ce1df0e-86a3-e544-743a-f357ff663f68%402ndquadrant.com

src/backend/utils/adt/numeric.c
src/test/regress/expected/numeric.out

index eea42398541b019a990ab319a48f3d7dd34e235b..5f23f2afac86af1b8f51ded0bd7f12749824370e 100644 (file)
@@ -2946,6 +2946,10 @@ numeric_fac(PG_FUNCTION_ARGS)
    NumericVar  fact;
    NumericVar  result;
 
+   if (num < 0)
+       ereport(ERROR,
+               (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+                errmsg("factorial of a negative number is undefined")));
    if (num <= 1)
    {
        res = make_result(&const_one);
index b255be7c8520841c3667caf4ddb36a912534ad77..2f3ecb50a73372019b25d60be19a8fc22d63260c 100644 (file)
@@ -2345,14 +2345,6 @@ SELECT 0!;
 (1 row)
 
 SELECT -4!;
- ?column? 
-----------
-        1
-(1 row)
-
+ERROR:  factorial of a negative number is undefined
 SELECT factorial(-4);
- factorial 
------------
-         1
-(1 row)
-
+ERROR:  factorial of a negative number is undefined