Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Tsql SQL:打印两个数字的公因数?_Tsql - Fatal编程技术网

Tsql SQL:打印两个数字的公因数?

Tsql SQL:打印两个数字的公因数?,tsql,Tsql,假设我想知道20和40这两个数字的所有公因数,然后写一个脚本将它们打印到屏幕上。我知道我可以使用MOD进行除法,这样我就可以对20和40中的每个数字进行除法,然后检查是否有重复项并打印出来,但这需要很多行,有没有更快的方法?如果数据库中有一个数字表(始终是一个很好的工具),那么您可以使用下面的T-SQL轻松完成此操作: declare @num1 int = 20; declare @num2 int = 40; select n.num as commonFactor from dbo.N

假设我想知道20和40这两个数字的所有公因数,然后写一个脚本将它们打印到屏幕上。我知道我可以使用MOD进行除法,这样我就可以对20和40中的每个数字进行除法,然后检查是否有重复项并打印出来,但这需要很多行,有没有更快的方法?

如果数据库中有一个数字表(始终是一个很好的工具),那么您可以使用下面的T-SQL轻松完成此操作:

declare @num1 int = 20;
declare @num2 int = 40;


select n.num as commonFactor
from dbo.Nums as n
where (n.num < case when @num1 > @num2 then @num1 else @num2 end)
    and @num1 % n.num = 0
    and @num2 % n.num = 0
declare@num1 int=20;
声明@num2 int=40;
选择n.num作为公共因子
来自dbo.Nums作为n
式中(n.num<当@num1>时的情况@num2然后@num1 else@num2 end)
和@num1%n.num=0
和@num2%n.num=0

如果您没有数字表,那么创建一个数字表就很容易了-请看几个例子

太棒了,谢谢!你知道模(%)运算符是如何工作的吗?有人说这很容易,但没有解释模算子是如何被解释的