필터 지우기
필터 지우기

How do I execute this problem?

조회 수: 6 (최근 30일)
Thobeka Radebe
Thobeka Radebe 2016년 5월 5일
편집: Daniel 2016년 5월 6일
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.

답변 (1개)

Daniel
Daniel 2016년 5월 6일
편집: Daniel 2016년 5월 6일
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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by