-2

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.

myg
  • 3
  • 6

1 Answers1

1

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.

Update

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}

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
  • 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. – myg Aug 11 '16 at 16:39
  • @myg, "I do not want a1 and a2 included in the output" - then use Drop[]. For your other concern, look up NestWhileList[]. – J. M.'s missing motivation Aug 11 '16 at 17:10