Re: factorial

From: --CELKO-- <71062.1056_at_compuserve.com>
Date: 15 Jan 2002 11:49:44 -0800
Message-ID: <c0d87ec0.0201151149.61acc632_at_posting.google.com>


Another thought and two handy tricks:

  1. One of the standard auxillary tables yuou build when you get a new data base is a simple sequence of Integers. It is handy for a lot of queries

CREATE TABLE Sequence (seq INTEGER NOT NULL PRIMARY KEY); INSERT INTO Sequence VALUES (1), (2),... (n);

2) Here is a version of the aggregate product function in SQL. You will need to have the logorithm and exponential functions. They are not standards, but they are very common.

The idea is that there are three special cases - all positive numbers, one or more zeroes, and some negative numbers in the set. You can find out what your situation is with a quick test on the sign() of the minimum value in the set.

Within the case where you have negative numbers, there are two sub-cases: (1) an even number of negatives or (2) an odd number of negatives. You then need to apply some High School algebra to determine the sign of the final result.

SELECT CASE MIN (SIGN(nbr))

       WHEN 1 THEN EXP(SUM(LN(nbr))) -- all positive numbers 
       WHEN 0 THEN 0.00                 -- some zeroes 
       WHEN -1                          -- some negative numbers 
       THEN (EXP(SUM(LN(ABS(nbr)))) 
             * (CASE WHEN 
                     MOD (SUM(ABS(SIGN(nbr)-1)/ 2)), 2) = 1
                     THEN -1.00 ELSE 1.00 END) 
       ELSE NULL END AS big_pi

 FROM NumberTable;

3) we put the two tricks together, withthe assumption that we have only positive numbers.

CREATE TABLE Factorials (fact INTEGER NOT NULL PRIMARY KEY);

INSERT INTO Factorials
SELECT seq FROM Sequence;

INSERT INTO Factorials
SELECT CAST (EXP(SUM(LN(seq))AS INTEGER) -- all positive numbers   FROM Sequence AS S1, Factorial AS F1

 WHERE S1.seq <= F1.fact;

This is not recursive, nor is it procedural -- it is a set oriented solution. Received on Tue Jan 15 2002 - 20:49:44 CET

Original text of this message