Write a script that calculates the common factors between 18 and 54. To find a c
ID: 3740511 • Letter: W
Question
Write a script that calculates the common factors between 18 and 54. To find a common factor, you can use the modulo operator (%) to check whether a number can be evenly divided into both numbers. Hint, test will be something like 12 % 3 = 0 and 30 % 3 = 0 , the modulo gives you the remainder,if the remainder is zero then it is a factor. ie 10 and 30 are both divisible by 3. 4 is not a common factor because it does not divide evenly into both numbers. You will need a loop to complete this easily . Murach, Chapter 14, SQL
Explanation / Answer
/*Declaring variables for numbers 18 and 54*/
DECLARE @number1 int = 18;
DECLARE @number2 int = 54;
/*Initializing commonfactor to start with 1*/
DECLARE @commonfactor INT = 1;
/*Looping till commonfactor is less than or equal to the first number*/
WHILE @commonfactor <= @number1
BEGIN
/*Condition to check whether the commonfactor divides both the numbers*/
IF (@number1 % @commonfactor = 0 and @number2 % @commonfactor = 0)
/*Print each of the commonfactor if it divides both the numbers*/
PRINT @commonfactor
/*Increment the commonfactor*/
set @commonfactor = @commonfactor + 1
END
Sample Output:
1
2
3
6
9
18
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.