用T-SQL流程控制语句编写程序,求两个数的最大公约数和最小公倍数

刚接触数据库,还不是很会!那位高手可以帮忙?谢了!
DECLARE @a int,@b int,@c int,@d int
SET @a=15
SET @b=9
SET @c=@a%@b
SET @d=@a*@b
WHILE @c!=0
BEGIN
SET @a=@b
SET @b=@c
SET @c=@a%@b
IF @c=0
BREAK
ELSE
CONTINUE
END
SELECT @b,@d/@b
GO
这个是老师给的答案还有其他的方法吗?

可以定义两个函数来求最大公约数和最小公倍数,程序如下

/*求两个数的最大公约数*/
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
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-02-03
可以定义两个
函数
来求
最大公约数

最小公倍数
,程序如下
/*求两个数的最大公约数*/
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

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网