How do I execute this problem?

3 visualizaciones (últimos 30 días)
Thobeka Radebe
Thobeka Radebe el 5 de Mayo de 2016
Editada: Daniel el 6 de Mayo de 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.

Respuestas (1)

Daniel
Daniel el 6 de Mayo de 2016
Editada: Daniel el 6 de Mayo de 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

Categorías

Más información sobre Functions en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by