Matlab Tutorials | Examples
Practice 4:
Pairs that have common divisors
Write a MATLAB program that does the following jobs:
- Get two whole numbers (a and b) greater than 1. If any of the numbers do not satisfy the criteria, display a warning message and stop the program.
- For all pairs of numbers between [a…b] (both inclusive) find all positive common divisors greater than 1 and display them as in the sample output below.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
% Start to giving inputs from user num1 = input('What is the first number: '); num2 = input('What is the second number: '); %Checking the number is whole and orders if (num1 == ceil(num1)) && (num2 == ceil(num2)) && (num1 > 1) && (num2 > 1) %If num1 is bigger than num2 swap them for algorithm if num1>num2 temp = num1; num1 = num2; num2 = temp; end %CHeck the each numbers between num1 and num2 and checking the %divisibity for a=num1:num2 for b=a+1 : num2 for i=2 : num2 if(mod(a,i)==0 && mod(b,i) ==0) fprintf('%g and %g are divisible by %g\n',a,b,i) end end end end else disp('You must provide whole numbers greater than 1.') end |