Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 Script Library
 GCD and LCM functions

Author  Topic 

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2009-04-14 : 12:34:21
Couldn't find a lowest common multiple function here so posting one. As it's functional it only deals with 32 nested levels. Can't take any credit for this -- just copied an algorithm from wikipedia!


IF OBJECT_ID('dbo.gcd') IS NOT NULL DROP FUNCTION dbo.gcd
GO

CREATE FUNCTION dbo.gcd (@a INT, @b INT) RETURNS INT AS BEGIN
IF @b = 0 RETURN @a
ELSE RETURN dbo.gcd(@b, @a % @b)
RETURN -1
END
GO

IF OBJECT_ID('dbo.lcm') IS NOT NULL DROP FUNCTION dbo.lcm
GO

CREATE FUNCTION lcm(@a INT, @b INT) RETURNS INT AS BEGIN
RETURN (@a * @b) / dbo.gcd(@a, @b)
END
GO



Charlie
===============================================================
Msg 3903, Level 16, State 1, Line 1736
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2009-04-14 : 12:55:43
Sorry to disturb the peace...
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

EDIT: Some extra error checking


E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2009-04-15 : 04:12:21
Cheers Peso -- that one looks a little more robust than the one I posted.





Charlie
===============================================================
Msg 3903, Level 16, State 1, Line 1736
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION
Go to Top of Page
   

- Advertisement -