Clear Filters
Clear Filters

remainder while dividing a number by x number of digits

2 views (last 30 days)
if i have a line of code like this
while(rem(i,2) ~= 0 || rem(i,3) ~= 0 || rem(i,4) ~= 0
its OK if I know the limit of 'i' , what can I do to make i open ended such that I can input 'i' as any number and the while loop will be performed . E.G i = 30 , the the while loop continues up to 'rem(1,4)~=0'
  3 Comments
OLUBUKOLA ogunsola
OLUBUKOLA ogunsola on 23 Jun 2016
yes, there is in between its in the for while(rem(i,2) ~= 0 ||rem(i,3) ~= 0 ||rem(i,4) ~= 0
Guillaume
Guillaume on 23 Jun 2016
Olubukola, bars, |, in posts have special meaning (they format text like this) Therefore, even though you wrote them they did not appear.
If you format your code as code by pressing the {}Code button above the post, then they'll show up as intended.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 23 Jun 2016
Edited: Guillaume on 23 Jun 2016
Avoid using i as a variable name, it's meaningless and it's also a function in matlab.
To answer your question, use vectorised operations with any:
numdigits = 30; %your limit
value = 150; %your i
%test value against all numbers between 1 all at once (use array 1:numdigits)
%if ANY of the remainder is not 0, do something
while any(rem(value, 2:numdigits))
%do something
end
  2 Comments
OLUBUKOLA ogunsola
OLUBUKOLA ogunsola on 23 Jun 2016
Edited: Guillaume on 23 Jun 2016
@Guillaume , i'm sorry I don't understand where 'value=150' fits in . this is the code i'm trying to adjust to fit what i'm trying to achieve
while(rem(i,2) ~= 0 || rem(i,3) ~= 0 || rem(i,4) ~= 0 || ...
rem(i,5) ~= 0 || rem(i,6) ~=0 || rem(i,7) ~= 0 || rem(i,8) ~= 0 ...
|| rem(i,9) ~= 0 || rem(i,10) ~= 0 || rem(i,11) ~= 0 ...
|| rem(i,12) ~= 0 || rem(i,13) ~= 0 || rem(i,14) ~= 0 ...
|| rem(i,15) ~= 0 || rem(i,16) ~= 0 || rem(i,17) ~= 0 ...
|| rem(i,18) ~= 0 || rem(i,19) ~= 0 || rem(i,20) ~= 0)
i = i+20;
in my own code i want the user to determine where we will stop, not like in this case where it is 20.
Guillaume
Guillaume on 23 Jun 2016
Edited: Guillaume on 23 Jun 2016
value is the variable you've called i, I just gave it a better name.
Your code is equivalent to:
while any(rem(i, 2:20))
i = i + 20;
rem(i, 2:20) will result in a vector of the remainders of i divided by the integers 2 to 20. any on that vector will be true if any of then is not zero.
But please, use a better variable name than i.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!