MS SQL计算最大公约数和最小公倍数函数

/*求两个数的最大公约数*/
CREATE  FUNCTION f_GetGys
    (
      @num1 BIGINT ,
      @num2 BIGINT
    )
RETURNS BIGINT
AS
    BEGIN
        DECLARE @m BIGINT;
        DECLARE @i BIGINT;
        IF ( @num1 < @num2 )--确保@num1永远是大的 @num2永远是小的
            BEGIN 
                SET @m = @num2; 
                SET @num2 = @num1;
                SET @num1 = @m; 
            END; 
        SET @i = @num1 % @num2;
        WHILE @i > 0
            BEGIN 
                SELECT  @num1 = @num2 ,
                        @num2 = @i ,
                        @i = @num1 % @num2;
            END; 
        RETURN @num2;
    END;
GO
/*求两个数的最小公倍数(调用了最大公约数函数,也可以直接写进去)*/
CREATE  FUNCTION f_GetGbs
    (
      @num1 BIGINT ,
      @num2 BIGINT
    )
RETURNS BIGINT
AS
    BEGIN 
        DECLARE @a BIGINT;
        DECLARE @b BIGINT;
        DECLARE @c BIGINT;
        DECLARE @d BIGINT;  
        SET @a = @num1; 
        SET @b = @num2;
        SET @c = dbo.f_GetGys(@num1, @num2);
        SET @d = @a * @b / @c;
        RETURN @d;
    END;
GO


摘自:http://bbs.csdn.net/topics/380047119


posted @ 2016-09-21 09:46  网事  阅读(1054)  评论(0编辑  收藏  举报