no的阶乘之和[关闭]

问题描述 投票:-5回答:4

想要找到num的阶乘数字的总和?

但我需要结果的总和,如5!这是120我想要1 + 2 + 0 = 3

sql sql-server sql-server-2008
4个回答
1
投票

这可以通过递归CTE来实现:

--here you decide what factorial to calculate
declare @i int = 5;
;with cte as(
    select 1 n, 1 factorial
    union all
    select n + 1, factorial * (n + 1) from cte
    where n < @i
)
select factorial,
       --just to make sure we correctly sum all digits
       (factorial%100000)/10000 + 
       (factorial%10000)/1000 + 
       (factorial%1000)/100 + 
       (factorial%100)/10 + 
       factorial%10 DigitsSum
from cte
where n = @i

0
投票

你可以使用这样的代码:

declare @a int
set @a = 120
declare @temp varchar(20)
set @temp = cast(@a as varchar(20))
declare @Result int
set @Result = 0
declare @tempLength int
set @tempLength = DATALENGTH(@temp)
while @tempLength > 0
begin
    set @Result = @Result + cast(SUBSTRING(@temp, @tempLength, 1) as int)
    set @tempLength = @tempLength - 1
end
select @Result

变量“a”与您的因子结果相同。


-1
投票

尝试substring()函数并分开数字,然后将所有数字加在一起。


-1
投票

你可以从sum of factorial of the no创建一个函数来找出一个数字的因子。然后使用下面的查询来查找Sum:

    DECLARE @var1 int   
    select @var1 = dbo.Factorial(5)

    ;WITH i AS (
        SELECT @var1 / 10 n, @var1 % 10 d

        UNION ALL

        SELECT n / 10, n % 10
        FROM i
        WHERE n > 0
    )
    SELECT SUM(d)
    FROM i;
© www.soinside.com 2019 - 2024. All rights reserved.