栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

SQL素数函数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SQL素数函数

正如您所说,您可以拥有一个表格,其中存储着最多1000万个素数。然后,查找一个数字是否为质数将是微不足道的。然后的问题是哪种方法会更快。我怀疑桌子会快很多(我还没有测试过这个说法)。

同样在这里。提供了一些解决方案。

SQL函数解决方案

解决方案0

这是通过使用Transact-SQL函数查找素数的一种解决方案:

SET ANSI_NULLS onGOSET QUOTED_IDENTIFIER ONGO–- =============================================–- Author:        Nicolas Verhaeghe–- Create date: 12/14/2008–- Description:   Determines if a given integer is a prime–- =============================================CREATE FUNCTION [dbo].[isPrime](      @NumberToTest int)RETURNS bitASBEGIN      -–Declare the return variable here      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 @IsPrimeEND

解决方案1

这是通过使用一个select语句查找素数或非素数的另一种解决方案?其他评论中也有更多信息。

CREATE FUNCTION isPrime(    @number INT)RETURNS VARCHAr(10)BEGIN    DECLARE @prime_or_notPrime INT    DECLARE @counter INT    DECLARE @retVal VARCHAr(10)    SET @retVal = 'FALSE'    SET @prime_or_notPrime = 1    SET @counter = 2    WHILE (@counter <= @number/2 )    BEGIN        IF (( @number % @counter) = 0 )        BEGIN set @prime_or_notPrime = 0 BREAK        END        IF (@prime_or_notPrime = 1 )        BEGIN SET @retVal = 'TRUE'        END        SET @counter = @counter + 1    END    return @retValEND


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/368619.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号