Reputation: 1
I am going to find gcd of two integer numbers by using SQL stored procedure with recursion query. But I got stuck in a loop and I really don't know why, here is my code:
create or alter procedure sp_gcd
@s1 int, @s2 int
as
begin
if (@s1 % @s2 = 0)
print @s2
else if (@s2 % @s1 = 0)
print @s1
else
begin
while (@s2 % @s1 != 0)
begin
declare @temp int = @s2 % @s1
exec sp_gcd @temp, @s1
end
print @s1
end
end
exec sp_gcd 15,21
And this is the result:
3
3
3
3
3
3
3
3
3
...
I just start working with SQL so I will very much appreciate if anyone could help, thanks a lot.
Upvotes: 0
Views: 338
Reputation: 433
stack calls:
sp_gcd 15 21
sp_gcd 6 15
sp_gcd 3 6
print 3
sp_gcd 3 6
print 3
sp_gcd 3 6
print 3
The reason for this to happen is that the while loop, inside the procedure call sp_gcd 6 15, never reaches the false condition; that is, the condition 15 % 6!=0
is always true.
Upvotes: 1