Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In TSQL, Find the greatest common factors of two numbers. For this assignment, y

ID: 3706383 • Letter: I

Question

In TSQL, Find the greatest common factors of two numbers.

For this assignment, you’ll need to create variables and set them to two different numbers. The expected output should look something like:

“The greatest common divisor for <#your first number> and <#your second number> is: <#the answer>”

A couple of examples that you can use to test your code with:

GCD for 25 and 20 is 5

GCD for 103 and 31 is 1

GCD for 18 and 36 is 18

You can't use any built in functions.

You only need to worry about positive numbers between 1 and 1000. Your algorithm doesn’t have to be super-efficient.

Explanation / Answer

CREATE FUNCTION dbo.fnGCD

(

            @a INT,

            @b INT

)

RETURNS INT

AS

BEGIN

            DECLARE     @c INT

            IF @a IS NULL OR @b IS NULL OR (@a = 0 AND @b = 0)

                         RETURN NULL

            IF @a = 0 OR @b = 0

                         RETURN ABS(@a) + ABS(@b)

            IF ABS(@a) < ABS(@b)

                         SELECT      @c = ABS(@a),

                                     @a = ABS(@b),

                                     @b = @c

            ELSE

                         SELECT      @a = ABS(@a),

                                     @b = ABS(@b)

            SET         @c = @a % @b

            WHILE @c > 0

                         SELECT      @a = @b,

                                     @b = @c,

                                     @c = @a % @b

            RETURN      @b

END

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote