Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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
up vote 3 down vote accepted

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

You need to use

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




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


{6, 11}

as expected.

To take another example:

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


 Select[Range[5], Not[EvenQ[#]]&]
 (* { 1, 3,5 }*)
share|improve this answer
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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