Message Boards Message Boards

0
|
5227 Views
|
5 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Can somebody help me on building up my LOOP structure?

Posted 10 years ago

Can somebody help me on finalizing my loop structure? I am looking for a loop that will BREAK when I get an integer results and print that result

I tried that one but it does not work Can you improve it?

Do[If[IntegerQ[107/i],Print[107/i],{i,2,8,2}]

Thanks for your help

Louis

POSTED BY: Louis Piche
5 Replies

You need a right bracket to close the If statement.

Do[If[IntegerQ[107/i], Print[107/i]], {i, 1, 8}]

107

POSTED BY: Frank Kampas

Note that the approach does not actually break when the value is reached (and in the original case illustrated it will never result in a returned value since 107 is not even). The Do loop will go until the end whether or not the value in the first argument of the If statement is satisfied. An approach like this (without a Print statement since you want a returned value rather than a byproduct of the Do loop as a printed statement) will satisfy what you are looking for (using 14291 as a test case and returning both the value of i where it achieves its IntegerQ requirement and the result of that requirement):

Catch@Do[If[IntegerQ[14291/i], Throw[{i, 14291/i}]], {i, 2, 14291}]

And if you actually wanted to go through the whole Do loop and get all instances where the If statement evaluated to True you could use Reap and Sow like this:

Reap@Do[If[IntegerQ[14291/i], Sow[{i, 14291/i}]], {i, 2, 14291}]

Note that the first element of the list that is returned is Null because the Do loop does not return results--it just evaluates its argument.

POSTED BY: David Reiss
Posted 10 years ago
POSTED BY: Louis Piche
Posted 10 years ago

Sir,

Thanks. You are right. I forgot a bracket for the If.

Can you help me on the following (I got this from David Reiss which was a very good response)? I would like to insert a BREAK as soon as a first factor is found out, print on the screen and also print the result from my printing machine.

Catch@Do[If[IntegerQ[14291/i], Throw[{i, 14291/i}]], {i, 2, 14291}]

ALSO, From a new command line, to get all the results of the divisions along with decimals (maximum of 5 decimals) and print on the screen and from my printing machine.

Thanks for your reply, Have a good day

POSTED BY: Louis Piche
Posted 7 years ago

Any can help, Sir, Can you help me on? The input is: Do[If[IntegerQ[121/i], Print[i]],{i,2,11}] The output will be: 11 BUT I would like to get an output such as "No Solution" if I have the following Input Do[If[IntegerQ[121/i], Print[i]],{i,2,7}] I want to print an output : "No Solution" How and where to insert the code? Thanks for your help ____________

POSTED BY: Louis Piche
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract