Stored procedure to calculate factorial with natural logarithm

This site has shown stored procedure and function to calculate factorial with SQL. Although the logic is so simple as extracting one from previous argument and multiplying to it, it requires high cost of computing power. Therefore, the maximum of argument is restricted to so relatively small integer. In this article, you can calculate factorial with converting argument to natural logarithm, adding them and re-converting it to power of e, the base of natural logarithm.

CREATE PROCEDURE [dbo].[LOG_FACT]
    @SrcNumber    FLOAT
AS
BEGIN
    DECLARE	@DesNumber    FLOAT
    SET @DesNumber = LOG(1)
    WHILE @SrcNumber > 0
    BEGIN
        SET @DesNumber = @DesNumber + LOG(@SrcNumber)
        SET @SrcNumber = @SrcNumber - 1
    END
    SELECT	EXP(@DesNumber)
END

Maximum of argument is 170.

EXEC LOG_FACT 170;
7.25741561530971E+306

対数により階乗を計算するストアドプロシージャを作成する

 SQL で階乗を計算するストアドプロシージャにはSQL-Serverの関数・プロシージャのVB.NETでの実行などのサイトがありますが,入力できる引数の上限が比較的小さくあまり実用的ではありません.引数から1ずつ減算して前の値に掛けていくという計算のロジックは比較的シンプルですが,計算コストは逆に高くなります.ここでは引数を一旦自然対数に変換して対数の和を求め,最後に自然対数の底のべき乗を求めることで階乗を求めます.

CREATE PROCEDURE [dbo].[LOG_FACT]
    @SrcNumber    FLOAT
AS
BEGIN
    DECLARE	@DesNumber    FLOAT
    SET @DesNumber = LOG(1)
    WHILE @SrcNumber > 0
    BEGIN
        SET @DesNumber = @DesNumber + LOG(@SrcNumber)
        SET @SrcNumber = @SrcNumber - 1
    END
    SELECT	EXP(@DesNumber)
END

 引数に取りうる最大値は170です.

EXEC LOG_FACT 170;
(列名なし)
7.25741561530971E+306