日期:2014-05-18  浏览次数:20413 次

来用SQL语句算最大公约数了 分不多 就100...!
请用SQL语句求下列两个数的最大公约数:::


4294967294 3465465468



------解决方案--------------------
SQL code
/*求两个数的最大公约数*/
create function GetGys(@num1 int,@num2 int)
returns int --返回值
as
begin
declare @times int  --计数器
declare @min int    --存储两个数的较小者
declare @result int  --保存结果
if(@num1>=@num2)
set @min=@num2
else
set @min=@num1
set @times=@min
while(@times<=@min) --循环
begin
if(@num1%@times=0 and @num2%@times=0)
begin
set @result=@times
break
end
set @times=@times-1
end
return @result
end


/*求两个数的最小公倍数*/
create function GetGbs(@num1 int,@num2 int)
returns int
as
begin
declare @result int  --结果
declare @max int  --保存两个数的大者
declare @times int
if @num1<=@num2
set @max=@num2
else
set @max=@num1
set @times=@max
while(@times>=@max)
begin
if(@times%@num1=0 and @times%@num2=0)
begin
set @result=@times
break
end
set @times=@times+1
end
return @result
end 

最后测试:
运行
select dbo.GetGys(15,20) as 最大公约数,dbo.GetGbs(15,20) as 最小公倍数

显示结果:
最大公约数      最小公倍数
   5                60赞同23| 评论

------解决方案--------------------
SQL code
GO
Create FUNCTION fn_num(@a BIGINT,@b BIGINT)
RETURNS BIGINT
AS
BEGIN
    DECLARE @c BIGINT
    SET @c=@a%@b
    WHILE @c>0
        select @a=@b,@b=@c,@c=@a%@b
    RETURN @b
END
GO

SELECT dbo.fn_num(4294967294,3465465468)