Given numbers a1 and a2 and a positive integer k, such that a3 = Mod[a1 a2, k], a4 = Mod[a1 a3, k] and so on, I want the Mathematica code that can compute the value of {a1, a2, a3, a4, ..., an} stopping at a point where a particular condition is met.

  • 1
    $\begingroup$ Look up NestList[]. If your actual problem is the implementation of an MLCG, look up the docs for SeedRandom[]. $\endgroup$ – J. M. will be back soon Aug 11 '16 at 15:18

In Mathematica this sort of computation is usually done with NestList. Here is an example.

With[{k = 7, a = 3, b = 5, n = 11}, Prepend[NestList[Mod[a #, k] &, b, n], a]]

{3, 5, 1, 3, 2, 6, 4, 5, 1, 3, 2, 6, 4}

Note this shows a cycle length of 7, the maximum length possible with k = 7.


I add this to meet the additional requirements stated by the OP in a comment below.

generator[a1_, a2_, k_, test_] := 
  Rest @ NestWhileList[Mod[a1 #, k] &, a2, test, 1, 2 k]
generator[3, 5, 7, # != 2 &]

{1, 3, 2}

  • $\begingroup$ thanks for that prompt reply but first, I do not want a1 and a2 included in the output. Secondly, I would like the computation to stop at a point say where an is 2 first which in your example above is at n=3 excluding a1 and a2. Thanks in advance. $\endgroup$ – myg Aug 11 '16 at 16:39
  • $\begingroup$ @myg, "I do not want a1 and a2 included in the output" - then use Drop[]. For your other concern, look up NestWhileList[]. $\endgroup$ – J. M. will be back soon Aug 11 '16 at 17:10

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.