[dba-SQLServer] I Finally Figured Out A Use For The Modulo Function

Alan Lawhon lawhonac at hiwaay.net
Mon Oct 24 00:33:48 CDT 2011


Use integer arithmetic with the modulo function to determine if an integer
is a prime number - of course!!  (I almost feel like a programmer again.)
J)))

 

Alan C. Lawhon

 

--

--  Figure out how to convert this script to a function and pass the prime
number

--  candidate in as a parameter.

--

USE AP

GO

DECLARE @Prime_Number_Candidate AS int, @Y AS int, @Quotient AS int,
@Remainder AS int

SET @Prime_Number_Candidate = 29

--

--  Next two IF statements prevent a division by zero run-time error if

--  @Prime_Number_Candidate just happens to be set to one.

--

IF (@Prime_Number_Candidate = 1)

     SELECT CONVERT(varchar, @Prime_Number_Candidate) + ' is a PRIME
number.'

IF (@Prime_Number_Candidate = 1)

     RETURN

--

SET @Y = @Prime_Number_Candidate - 1

SET @Quotient = @Prime_Number_Candidate/@Y

SET @Remainder = @Prime_Number_Candidate%@Y

--

WHILE @Y > 1

      BEGIN

           SET @Quotient = @Prime_Number_Candidate/@Y

           SET @Remainder = @Prime_Number_Candidate%@Y

           IF (@Quotient > 1 AND @Remainder = 0)

                SELECT @Prime_Number_Candidate AS Prime_Number_Candidate, @Y
AS Prime_Candidate_Minus_1,

                       @Quotient AS Quotient, @Remainder AS Remainder

           IF (@Quotient > 1 AND @Remainder = 0)

                SELECT CONVERT(varchar, @Prime_Number_Candidate) + ' is NOT
a prime number.'

           IF (@Quotient > 1 AND @Remainder = 0)

                SELECT CONVERT(varchar, @Prime_Number_Candidate) + ' is
evenly divisible by ' + 

                       CONVERT(varchar, @Y) + '.'

           IF (@Quotient > 1 AND @Remainder = 0)

                RETURN

           SET @Y = (@Y -1)

      END      

--

IF (@Y = 1)

     SELECT CONVERT(varchar, @Prime_Number_Candidate) + ' is a PRIME
number.'

IF (@Y = 1)

     RETURN

 




More information about the dba-SQLServer mailing list