code to find the first whole number divisible by 1 to n

Greetings!!! :)
Can someone edit the following code to ask a user the number (n)?; where the code could run and find the first whole number divisible by all the numbers from 1 to n. Below example displays the first whole number which is divisible by all the numbers from 1 to 13.
***********
function first_whole_number
i=1;
while i>=0
if mod(i,2)==0 && mod(i,3)==0 && mod(i,4)==0 && mod(i,5)==0 && mod(i,6)==0 && mod(i,7)==0 && mod(i,8)==0 && mod(i,9)==0 && mod(i,10)==0 && mod(i,11)==0 && mod(i,12)==0 && mod(i,13)==0
break;
else
i=i+1;
end
end
fprintf('\n\nthe first whole number divisible by 1 to 13 is %d\nThankyou\n\n\n',i);
end
**********
THANKYOU :)

 Accepted Answer

the mod function accepts a vector for the second argument, you can use this to check for a sequence of factors, e.g.:
if(any(mod(i,[2:n])))
i=i+1;
else
break;
end
However, this can become very slow and you might think about a more mathematical solution instead of checking every number.

3 Comments

Maybe as a little idea ... one number that will always be divisible by all numbers from 1 to n is of course n! (factorial). However, it's not the the smallest because when multiplying 1 * 2 * 3 *4 * ... * n some of these numbers will share common factors, e.g. 2 and 4. If something is divisible by 4 it is already divisible by 2 and you can strike the 2 completely in the product 1 * 3 * 4 *... *n . So instead of checking the product, you might want to think about checking the potential factors for the number in question. Hope that helps, good luck with the task.
wow!thankyou for the perfect code.
and now i modified it again without using function 'any'.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming 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!