2
$\begingroup$

I want to define a $f$ function on Mathematica such as this. $f[k]$ gives the smallest $m$ holds $2k=Prime[m+1]-Prime[m]$. For example,

$$f[1]=2$$ $$f[2]=4$$ $$f[3]=9$$ $$f[4]=24$$

How can i do that?

$\endgroup$
1
  • 1
    $\begingroup$ I can't see an easy way of doing it. You'd have to build a table or do a While loop or something. I assume you're looking for an easier solution than that, yes? $\endgroup$
    – user1722
    Jan 28, 2016 at 14:57

1 Answer 1

3
$\begingroup$

The sequence $f[k]$ you are looking for is Sloane's A038664. There is Mathematica code given there by Harvey P. Dale.

With[{d=Differences[Prime[Range[50000]]]},
     Flatten[Table[Position[d, 2n, 1, 1], {n, 50}]]]

which returns {2,4,9,24,34,46,30,...}.

$\endgroup$
2
  • $\begingroup$ 50000 is insufficient, can be seen thus: With[{d = Differences[Prime[Range[50000]]]}, Flatten[Table[ Position[d, 2 n, 1, 1], {n, 50}] /. {{} -> "FAIL"}]] $\endgroup$ Jan 28, 2016 at 23:07
  • $\begingroup$ Yes. For any range of primes, some gaps will not appear. Dale's code hides this by using Flatten to remove missing gaps. Your adjustment to include Fail before Flatten reveals the limitation. $\endgroup$ Jan 29, 2016 at 0:31

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.