【问题标题】:sum of factorial of the no [closed]没有的阶乘总和[关闭]
【发布时间】:2018-09-04 07:00:09
【问题描述】:

想求一个num的阶乘位数之和吗?

但我需要像 5 这样的结果的总和!是 120 在这个我想要 1+2+0=3

【问题讨论】:

标签: sql sql-server sql-server-2008


【解决方案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

【讨论】:

    【解决方案2】:

    你可以使用这样的代码:

    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”与您的阶乘结果相同。

    【讨论】:

      【解决方案3】:

      尝试 substring() 函数并分离数字,然后将所有数字相加。

      【讨论】:

        【解决方案4】:

        您可以从sum of factorial of the no 创建一个函数来找出一个数字的阶乘。 然后使用以下查询查找总和:

            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;
        

        【讨论】:

        • 所以这个答案!
        • 如果你要复制粘贴别人的答案,请至少也包括参考
        猜你喜欢
        • 2013-10-20
        • 2011-10-17
        • 1970-01-01
        • 2021-07-04
        • 2022-01-08
        • 1970-01-01
        • 2016-12-28
        • 1970-01-01
        • 2021-11-07
        相关资源
        最近更新 更多