27,580
社区成员




update GCD_LCM
set gcd=dbo.GetGys (a,b),lcm=dbo.GetGbs(a,b)
INSERT INTO GCD_LCM (gcd,lcm) SELECT dbo.GetGys (a,b),dbo.GetGbs(a,b) FROM GCD_LCM
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)
Dim a As UInteger = 4294967294
Dim b As UInteger = 3465465468
Dim c As UInteger
Do
c = a Mod b
If c = 0 Then Exit Do
a = b
b = c
Loop While c >= 1
MsgBox(b)
'结果b=2
/*求两个数的最大公约数*/
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
/*求两个数的最小公倍数(调用了最大公约数函数,也可以直接写进去)*/
ALTER 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
DECLARE @a bigint,@b bigint,@c bigint
SET @a=4294967294
SET @b=3465465468
SET @c=@a%@b
WHILE @c>0
select @a=@b,@b=@c,@c=@a%@b
SELECT @b
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 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| 评论