# How could I implement the equivalent of NextPrime

I would like to know what an implementation of the function NextPrime would look like if it were implemented in Mathematica's core language.

• Welcome to Mathematica.SE, Robert. What have you tried? It is preferable if you show some effort in working out your problem for yourself, and give some indication of where you got stuck. Please see the FAQ for more details. Jan 18 '13 at 3:42
• Are you looking for any one way to implement it or do you want to know how it is actually implemented? Jan 18 '13 at 4:44
• What Szabolcs means to say is... NextPrime IS actually implemented in Mathematica. Try Trace[NextPrime]. The core of it is quite similar to what I posted
– Rojo
Jan 18 '13 at 4:48

(nextPrime[#1] = #2) & @@@ {{-3, 2}, {-2, 2}, {-1, 2}, {0, 2}, {1, 2}, {2, 3}};
nextPrime[n_Integer?EvenQ] := nextPrime[n - 1];
nextPrime[n_Integer] /; PrimeQ[n + 2] := n + 2;
nextPrime[n_Integer] := nextPrime[n + 2]
nextPrime[n_ /; n \[Element] Reals] := nextPrime[Floor@n]

• There are only a few prime even integers. Perhaps you could take some advantage Jan 18 '13 at 4:37
• There you go @belisarius
– Rojo
Jan 18 '13 at 4:39
• Ok. You got the NextPrime yellow belt +1 Jan 18 '13 at 4:41
• @belisarius a few? Jan 18 '13 at 5:00
• @Mr.Wizard Well, my first English teacher was proud of me. He was deaf. Jan 18 '13 at 5:03

Just a joke:

nextp[i_] := Prime[PrimePi[i] + 1]

• somewhatNextPrime[x_] := FindInstance[\[FormalN] > x, \[FormalN], Primes]
– Rojo
Jan 18 '13 at 4:54

For reference, here is the v7 code behind NextPrime, which is hard to read before stripping all the private context names.

NextPrime; (* preload the definition *)
Unprotect[NextPrime];
$Context = "NumberTheoryNextPrimeDump"; FullDefinition[NextPrime]  Yields: Attributes[NextPrime] = {Listable} NextPrime[-3] := -2 NextPrime[-2] := 2 NextPrime[-1] := 2 NextPrime := 2 NextPrime := 2 NextPrime[n_Integer] := Block[{res}, res = integerNextPrime[n]; res /; IntegerQ[res]] NextPrime[r_] /; NumericQ[r] && ! IntegerQ[r] := Block[{res, n}, n = Quiet[Block[{$MaxExtraPrecision =
Max[$MaxExtraPrecision, 1 + Ceiling[Log[10., Abs[N[r]]]]]}, Floor[r]]]; (res = NextPrime[n]; res /; IntegerQ[res]) /; IntegerQ[n]] NextPrime[n_, k_Integer] /; NumericQ[n] && Positive[k] := Block[{res}, res = Nest[NextPrime, n, k]; res /; IntegerQ[res]] NextPrime[n_, k_Integer] /; NumericQ[n] && Negative[k] := Block[{res}, res = Nest[PreviousPrime, n, -k]; res /; IntegerQ[res]] NextPrime[n_?PrimeQ, 0] := n NextPrime[n_, 0] := NextPrime[n] NextPrime[n___] := (ArgumentCountQ[NextPrime, Length[{n}], 1, 2]; Null /; False) integerNextPrime[n_Integer] := Block[{res}, res = n + 1 + Mod[n, 2]; While[! PrimeQ[res], res += 2]; res /; IntegerQ[res]] integerNextPrime[___] :=$Failed