1
$\begingroup$

I want to find the smallest positive integer $k$ such that the finite list s[k*m] contains no odd numbers, for $m=1,2 \dots$. Unfortunately FindInstance is not working for me, so I am trying to use a For loop instead.

Right now, I have the loop For[k=1, Length[Select[s[k*m],OddQ]]!= 0, k++, x = k+1 ].

After I specify $m$ (say I set m=3) and run the above, I will have x equal to the number I want. However, if I want the next number, I must specify m=4, run the above again, and request x again.

This is quite tedious. Is there a way, similar to Table, to get the sequence I am looking for, for $m$ ranging from $1$ to some specified upper bound?

$\endgroup$
2
  • 2
    $\begingroup$ Table[For[k = 1, Length[Select[s[k*m], OddQ]] != 0, k++, x[m] = k + 1], {m, 1, 10}] $\endgroup$ – Bob Hanlon Nov 29 '20 at 19:49
  • $\begingroup$ You may also want to include the definition of s[k, m]. There might be another way than brute force. $\endgroup$ – MarcoB Nov 29 '20 at 19:56
2
$\begingroup$

Here is a solution with NestWhile.

To get a list:

Block[{s},
 s[l_] := 
  BlockRandom[SeedRandom[l]; 
   RandomChoice[{0.999, 0.001} -> {0, 1}, l]];
 
 Table[
  NestWhile[# + 1 &, 0, And @@ EvenQ[s[m #]] - 1 &],
  {m, 10}]
 ]

(*  {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}  *)

To get an association:

Block[{s},
 s[l_] := 
  BlockRandom[SeedRandom[l]; 
   RandomChoice[{0.999, 0.001} -> {0, 1}, l]];
 
 AssociationMap[
  Function[m,
   NestWhile[# + 1 &, 0, And @@ EvenQ[s[m #]] &] - 1
   ],
  Range@10]
 ]
(*
  <|1 -> 51, 2 -> 25, 3 -> 21, 4 -> 12, 5 -> 22, 
    6 -> 10, 7 -> 31, 8 -> 11, 9 -> 8, 10 -> 11|>
*)

To prevent runaway computations:

Block[{s, $maxIterations = 10}, (* 10000 might be a reasonable setting *)
 s[l_] := 
  BlockRandom[SeedRandom[l]; 
   RandomChoice[{0.999, 0.001} -> {0, 1}, l]];
 
 AssociationMap[
  Function[m,
   NestWhile[# + 1 &, 0, And @@ EvenQ[s[m #]] &, 1, $maxIterations] - 1 /.
     $maxIterations - 1 -> "$maxIterations"
   ],
  Range@10]
 ]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.