1

lets say that I want to know all of the common factors with two numbers, 20 and 40, and write a script that will print them to the screen. I know I can use MOD to divide so I could write out a division of every number out of both 20 and 40 and then check if there are duplicates and print them, but that would take a lot of lines, is there a quicker way?

1 Answers1

1

If you have a numbers table in your database (always a good tool to have) then you can easily do this with the T-SQL below:

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

If you don't have a numbers table then it is easy to create one - take a look at SQL, Auxiliary table of numbers for a few examples

Community
  • 1
  • 1
Paul McLoughlin
  • 2,283
  • 1
  • 15
  • 15