如何从列表中仅选择武器号码?

时间:2016-09-13 16:08:34

标签: sql sql-server

我想从下面的列表中选择阿姆斯壮数字我已经搜索过这个问题的解决方案无法在SQL-Server中找到:

Numbers
121
113
423
153
541
371

我相信你们大多数人都知道阿姆斯特朗的数字以及如何计算,虽然我所描述的是简单性:数字的立方数总和等于数字本身,即

1*1*1 + 5*5*5 + 3*3*3 = 153
3*3*3 + 7*7*7 + 1*1*1 = 371

请帮助我,因为我也在努力寻求快速解决方案。这对我很有帮助。提前谢谢。

4 个答案:

答案 0 :(得分:1)

这是我的数字总和UDF

的快速模式
Declare @Table table (Numbers int)
Insert into @Table values
(121),
(113),
(423),
(153),
(541),
(371)

Select * from @Table where [dbo].[udf-Stat-Is-Armstrong](Numbers)=1    

返回

Numbers
153
371

UDF

CREATE Function [dbo].[udf-Stat-Is-Armstrong](@Val bigint)
Returns Bit
As
Begin

Declare @RetVal as bigint
Declare @LenInp as bigint = len(cast(@Val as varchar(25)))
;with i AS (
    Select @Val / 10 n, @Val % 10 d
    Union ALL
    Select n / 10, n % 10
    From i
    Where n > 0
)
Select @RetVal = IIF(SUM(power(d,@LenInp))=@Val,1,0) FROM i;
Return @RetVal
End

答案 1 :(得分:1)

select  153 x into #temp;
insert #temp values(371);
insert #temp values(541);

with cte as (select x, substring(cast(x as nvarchar(40)) ,1,1) as u, 1 as N FROM #temp
            union all
            select x, substring(cast(x as nvarchar(40)),n+1,1) as u , n+1 from cte where len(cast(x as nvarchar(40))) > n
            )

    select x from cte group by x having SUM(POWER(cast(u as int),3)) = x


drop table #temp;

这里是标记2 - 你可以改变@ORDER以探索4,5等的力量

declare @order int = 3;
declare @limit int = 50000;

with        nos as (select 1 no 
            union all 
            select no + 1 from nos where no < @limit),          
            cte as (select no as x, substring(cast(no as nvarchar(40)) ,1,1) as u, 1 as N FROM nos
            union all
            select x, substring(cast(x as nvarchar(40)),n+1,1) as u , n+1 from cte where len(cast(x as nvarchar(40))) > n
            )

    select x from cte group by x having SUM(POWER(cast(u as int),@order)) = x
    option (maxrecursion 0);

答案 2 :(得分:1)

显然,每次查询期间的静态处理都不是正确的方法,但我们可以创建这样的函数和

create function dbo.IsArmstrongNumber(@n int)
returns int as 
begin 
    declare @retValue int = 0
    declare @sum int = 0
    declare @num int = @n
    while @num > 0
    begin
        set @sum += (@num%10) * (@num%10) * (@num%10)
        set @num = @num/10
    end 
    IF @sum = @n
        set @retValue = 1
    return @retValue
end

IN子句中的预处理和选择更好

select * from #Numbers where dbo.IsArmstrongNumber(n) = 1

答案 3 :(得分:0)

您可以使用以下命令使用Sql函数查找Armstrong数字:

WITH Numbers AS(
SELECT 0 AS number UNION ALL SELECT number + 1 FROM  Numbers  WHERE number < 10000)
SELECT number AS ArmstrongNumber FROM Numbers
WHERE
    number = POWER(COALESCE(SUBSTRING(CAST(number AS VARCHAR(10)),1,1),0),3)
           + POWER(COALESCE(SUBSTRING(CAST(number AS VARCHAR(10)),2,1),0),3)
           + POWER(COALESCE(SUBSTRING(CAST(number AS VARCHAR(10)),3,1),0),3)  
OPTION(MAXRECURSION 0)