Anda dapat, seperti yang Anda katakan, memiliki tabel yang menyimpan semua bilangan prima hingga 10 juta . Maka akan sepele untuk mencari apakah suatu bilangan prima atau tidak. Pertanyaannya kemudian adalah metode mana yang lebih cepat. Saya menduga tabelnya akan jauh lebih cepat (saya belum menguji klaim ini).
Solusi Tabel Utama
-
https:// www.simple-talk.com/sql/t-sql-programming/celkos-summer-sql-stumpers-prime-numbers/
Memberikan beberapa solusi dan masih banyak lagi di komentar. -
https:// sqlserverfast.com/blog/hugo/2006/09/the-prime-number-challenge-great-waste-of-time/
Sama di sini. Beberapa solusi disediakan.
Solusi Fungsi SQL
Solusi 0Inilah salah satu solusi melalui Menemukan bilangan prima dengan fungsi Transact-SQL :
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
–- =============================================
–- Author: Nicolas Verhaeghe
–- Create date: 12/14/2008
–- Description: Determines if a given integer is a prime
/*
SELECT dbo.IsPrime(1)
SELECT dbo.IsPrime(9)
SELECT dbo.IsPrime(7867)
*/
–- =============================================
CREATE FUNCTION [dbo].[isPrime]
(
@NumberToTest int
)
RETURNS bit
AS
BEGIN
-– 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 @IsPrime
END
Solusi 1 Berikut solusi lain melalui bagaimana menemukan apakah itu prima atau bukan prima dengan satu pernyataan pilih? Ada lebih banyak informasi di komentar lain juga.
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 @retVal
END