Message Boards Message Boards

0
|
2469 Views
|
2 Replies
|
1 Total Likes
View groups...
Share
Share this post:
GROUPS:

Basic infinite For loop.

Posted 11 years ago
I do not understand the flaw in my logic here. What I want is a list whose elements are integers with squares less than 1000 and that are prime.
----------------
 Clear[listPopulator];
 
 listPopulator := (
  
 Clear[intList];
   intList = {};
   For
    [
    k = 1,
   k^2 < 1000,
   k + 1,
   If[PrimeQ[k^2], AppendTo[intList, k], AppendTo[intList, k]]
   ];
  intList;
  )
-----------------
When I attempt to define this function I need to quit the kernel because I get stuck in an infinite loop (is what I'm assuming). My guesses are: 1) Maybe it's the fact my counter and control variable are the same. 2) Maybe intList being defined in the the function 'listPopulator' has something to do with it. I am going to experiment with these right now.

Also, I realize my 'false' statement in the If command makes no sense, but I wasn't sure what to put there if I wanted the If statement to do nothing in the case of a 'false'. At the moment I am more concerned with making sure intList is even populated.

Any tips would be helpful. Don't feel the need to 'give' me the answer.
POSTED BY: Fran Avit
2 Replies
Posted 11 years ago
Thank you! That turned out to be the problem. Thanks, also, for clarifying my If statement issue.
POSTED BY: Fran Avit
(1) I was able to prevent the "hang" with either k++ or k = k+1, rather than just k+1 for incrementing the value of k. (2) To avoid adding all the values to intList, you can choose to leave the "false" placeholder blank in the If[condition, do_if_true, do_if_false].
POSTED BY: Isaac Abraham
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