# Using NestWhileList to determine smallest prime value in series

I have a function recursively defined as follows:

$a_{n+1}-1=(a_n-1)\times lpf(a_n)$, whe $lpf(x)$ is the least prime factor of $x$.

Now, given an initial value of $a_0$, I would like to find the smallest value of $a_n$ such that $a_n$ is prime.

Here is my attempt at a code, with $a_0=6$.

NestWhileList[((#1 - 1)*FactorInteger[#1][[1, 1]] + 1) &, 6, ! PrimeQ]

However, my code always simply returns the initial value of $a_0$. What am I doing wrong here?

-
Maybe this Last@NestWhileList[((#1 - 1)*FactorInteger[#1][[1, 1]] + 1) &, 6, Not[PrimeQ[#]] &] ? – b.gatessucks Mar 2 '13 at 8:25
It seems that Not[PrimeQ[#]] & does the trick! Any idea why ! PrimeQ doesn't, however? – Vincent Tjeng Mar 2 '13 at 8:33

!PrimeQ is not a function. (Try, for example, (!PrimeQ)[3] )

You need to use

  !PrimeQ[#]& (* or Not[PrimeQ[#]]& as suggested by @b.gatessucks *)


or

  Composition[Not,PrimeQ]


Then

 NestWhileList[((#1 - 1)*FactorInteger[#1][[1, 1]] + 1) &, 6,
Composition[Not, PrimeQ]]


gives

{6, 11}


as expected.

To take another example:

 Select[Range[5], !EvenQ]
(* {} *)


while

 Select[Range[5], Not[EvenQ[#]]&]
(* { 1, 3,5 }*)

-
thank you! If I have a function as the above and would like to track how many iterations the function has taken so far, how would I implement the monitoring? I know about the Monitor function but am not sure how you would implement it here. – Vincent Tjeng Mar 2 '13 at 9:45
@vincent, thank you for the accept. About tracking the iterations, maybe j = 1; Monitor[ NestWhileList[(j++; ((#1 - 1)*FactorInteger[#1][[1, 1]] + 1)) &, yournumberhere, ! PrimeQ[#] &], j]? – kglr Mar 2 '13 at 10:03
yes, that's good for me. thank you! – Vincent Tjeng Mar 2 '13 at 10:30