Skip to content
Advertisement

While loop SQL Server

Help me please. I need to write two functions, one that calculates the factorial and another that calculates the sums of euler.

To make the euler sums I need to use the function that calculates the factory. I already have the function of factorial but when doing the sums the result I get “NULL”

Note: it needs to be done with “while” loop

e = 1 + (1/1!) + (1/2!) + (1/3!) + (1/n!)

My code:

CREATE FUNCTION Factorial (@a INT)
RETURNS INT 
AS
BEGIN
    DECLARE @i INT

    IF @a <= 1
        SET @i =1 
    ELSE
        SET @i = @a * dbo.Factorial(@a-1)

    RETURN @i
END

SELECT dbo.Factorial(11) 'factorial'

CREATE FUNCTION Sum_Euler(@a FLOAT)
RETURNS FLOAT
BEGIN 
    DECLARE @b FLOAT, 
            @c FLOAT;

    SET @c = (SELECT dbo.Factorial(@a))

    WHILE(@b <= @c)
    BEGIN
        SET @b = 1 / @a * @c
    END 

    SET @b = @b + 1

    RETURN @b
END
GO

SELECT dbo.Sum_Euler(10)

Advertisement

Answer

I’d make the following change to your second function

create FUNCTION dbo.Sum_Euler(@a int)
RETURNS float 
BEGIN 
    DECLARE @b float;
    if @a<=1
        set @b =1.0+1.0;
    else
    begin
      set @b = dbo.Sum_Euler(@a-1) + 1.0/dbo.Factorial(@a);
    end
        RETURN @b;

END
GO

select dbo.Sum_Euler(10) will return 2.718281801142

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement