How to check if an integer is a power of 3?

前端 未结 23 1127
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 08:15

I saw this question, and pop up this idea.

23条回答
  •  死守一世寂寞
    2020-12-02 08:34

    Set based solution...

    DECLARE @LastExponent smallint, @SearchCase decimal(38,0)
    
    SELECT
        @LastExponent = 79, -- 38 for bigint
        @SearchCase = 729
    
    ;WITH CTE AS
    (
        SELECT
            POWER(CAST(3 AS decimal(38,0)), ROW_NUMBER() OVER (ORDER BY c1.object_id)) AS Result,
            ROW_NUMBER() OVER (ORDER BY c1.object_id) AS Exponent
        FROM
            sys.columns c1, sys.columns c2
    )
    SELECT
        Result, Exponent
    FROM
        CTE
    WHERE
        Exponent <= @LastExponent
        AND
        Result = @SearchCase
    

    With SET STATISTICS TIME ON it record the lowest possible, 1 millisecond.

提交回复
热议问题