How do I execute this problem?

3 views (last 30 days)
Thobeka Radebe
Thobeka Radebe on 5 May 2016
Edited: Daniel on 6 May 2016
The smallest positive integer that can be divided by each of the number from 1 to 10 without leaving a remainder is 2520. In other words 2520 is the smallest positive number that has all the numbers from 1 to 10 as factors.
Write the Matlab code to find the smallest positive number that is divisible by all the number from 1 to 12 without leaving a remainder. Place the answer in a variable called resultA.

Answers (1)

Daniel
Daniel on 6 May 2016
Edited: Daniel on 6 May 2016
Hi Thobeka,
Here is one way to do it. Since this is for your homework you should figure out how to do it in a smarter way than this.
A top limit was chosen as 1,000,000 so it does't run forever
resultA = -1;
toplimit = 1000000;
Iterate through all even numbers from 2 to top limit until the value is found. The variables named after numbers store a boolean (either true or false). Check if the remainder of a division is zero using the mod(a,b) function. If all the numbered variables are true then store i into resultA and break out of the for loop.
for i = 2:2:toplimit
%in the variables named after the number use mod(a,b) to check if the
two = mod(i,2) == 0;
three = mod(i,3) == 0;
four = mod(i,4) == 0;
five = mod(i,5) == 0;
six = mod(i,6) == 0;
seven = mod(i,7) == 0;
eight = mod(i,8) == 0;
nine = mod(i,9) == 0;
ten = mod(i,10) == 0;
eleven = mod(i,11) == 0;
twelve = mod(i,12) == 0;
if two && three && four && five && six && seven && eight && nine && ten && eleven && twelve
resultA = i;
break;
end
end
Display the result to the command line.
if resultA ~= -1
fprintf('the smallest positive number that is divisible by all numbers from 1 to 12 is : %d\n',resultA);
else
fprintf('FAIL');
end

Categories

Find more on Functions in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!