Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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
1  
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
add comment

1 Answer

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 *)

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 }*)
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
1  
@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]? –  kguler Mar 2 '13 at 10:03
    
yes, that's good for me. thank you! –  Vincent Tjeng Mar 2 '13 at 10:30
add comment

Your Answer

 
discard

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.