您的位置:首页 > 数据库

[SQL] 利用函数(Function)判断输入的数是不是质数

2017-06-11 17:42 323 查看
作用: EN:Description: Determines if a given integer is a prime;

    JP:入力したデータが素数かどうか判断する;

    CN:判断输入的数是不是质数;
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =========================================================
-- Author     : http://blog.csnd.net/dietime1943 -- Create date: 06/11/2017
-- Description: EN:Determines if a given integer is a prime;
--              JP:入力したデータが素数かどうか判断する;
--              CN:判断输入的数是不是质数;
/*
SELECT dbo.udf_IsPrime(1)
SELECT dbo.udf_IsPrime(9)
SELECT dbo.udf_IsPrime(7867)
*/
-- =========================================================
CREATE FUNCTION [dbo].[udf_IsPrime]
(
@NumberToTest int
)
RETURNS bit
AS
BEGIN

DECLARE @IsPrime bit,
@Divider int

-- To speed things up, we will only attempt dividing by odd numbers

-- We first take care of all evens, except 2
IF (@NumberToTest % 2 = 0 AND @NumberToTest > 2)
SET @IsPrime = 0
ELSE
SET @IsPrime = 1 -- By default, declare the number a prime

-- We then use a loop to attempt to disprove the number is a prime

SET @Divider = 3 -- Start with the first odd superior to 1

-- We loop up through the odds until the square root of the number to test
-- or until we disprove the number is a prime
WHILE (@Divider <= floor(sqrt(@NumberToTest))) AND (@IsPrime = 1)
BEGIN

-- Simply use a modulo
IF @NumberToTest % @Divider = 0
SET @IsPrime = 0
-- We only consider odds, therefore the step is 2
SET @Divider = @Divider + 2
END

-- Return the result of the function
RETURN @IsPrime

END

参照文献:http://bbs.csdn.net/topics/390081893

注:本文原创由`bluetata`发布于blog.csdn.net、转载请务必注明出处。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: