Skip to content

Commit 0a40563

Browse files
committed
Disallow factorial of negative numbers
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
1 parent 9d402c7 commit 0a40563

File tree

2 files changed

+6
-10
lines changed

2 files changed

+6
-10
lines changed

src/backend/utils/adt/numeric.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2946,6 +2946,10 @@ numeric_fac(PG_FUNCTION_ARGS)
29462946
NumericVar fact;
29472947
NumericVar result;
29482948

2949+
if (num < 0)
2950+
ereport(ERROR,
2951+
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
2952+
errmsg("factorial of a negative number is undefined")));
29492953
if (num <= 1)
29502954
{
29512955
res = make_result(&const_one);

src/test/regress/expected/numeric.out

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2345,14 +2345,6 @@ SELECT 0!;
23452345
(1 row)
23462346

23472347
SELECT -4!;
2348-
?column?
2349-
----------
2350-
1
2351-
(1 row)
2352-
2348+
ERROR: factorial of a negative number is undefined
23532349
SELECT factorial(-4);
2354-
factorial
2355-
-----------
2356-
1
2357-
(1 row)
2358-
2350+
ERROR: factorial of a negative number is undefined

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy