I want to create my own functions, for example: Functions like IntegerQ,EvenQ and OddQ.

My code:

meuIntegerQ[_Integer] := True
meuIntegerQ[_] := False

meuEvenQ[n_Integer] /; (Mod[n, 2] == 0) := True
meuEvenQ[_] := False

meuOddQ[n_Integer] /; (Mod[n, 2] != 0) := True
meuOddQ[_] := False

Now I want to create meuPrimeQ. How can I create my own function that verify if the number is a Prime without using PrimeQ obviously (like the examples).


closed as off-topic by Daniel Lichtblau, Szabolcs, MarcoB, José Antonio Díaz Navas, Öskå Sep 9 '18 at 8:56

  • The question does not concern the technical computing software Mathematica by Wolfram Research. Please see the help center to find out about the topics that can be asked here.
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 5
    $\begingroup$ I'm voting to close this question as off-topic because it is more a math than Mathematica question. $\endgroup$ – Daniel Lichtblau Aug 31 '18 at 22:24

A simple but by far not the most efficient way is check whether any of the prime numbers $p$ numbers $2 \leq p \leq \lfloor\sqrt{n}\rfloor$ divides $n$ in a recursive way. In order to speed things up, I exploit memoization.

primeQ[1] = False;
primeQ[2] = True;
primeQ[n_] := primeQ[n] = Nor@@Divisible[n,Select[Range[2,Floor[Sqrt[n]]],primeQ]]

A test:

PrimeQ /@ Range[1000] == primeQ /@ Range[1000]


It more efficient, to use short circuiting when the first divisor of n is found, so that non-primes have a chance to be identified quite early:

primeQ2[1] = False;
primeQ2[2] = True;
primeQ2[n_] := primeQ2[n] = Block[{p = 1, b = True},
   While[b && p < Floor[Sqrt[N[n]]],
    b = If[primeQ2[p], Not[Divisible[n, p]], True];

A test with timings:

nmax = 100000;
a = PrimeQ /@ Range[nmax]; // AbsoluteTiming // First
b = primeQ /@ Range[nmax]; // AbsoluteTiming // First
c = primeQ2 /@ Range[nmax]; // AbsoluteTiming // First
a == b
a == c






The future runs of primeQ and primeQ2 will be faster since the intermediate results have all been stored.


@Mateus, technically satisfies your requirement! Also, unlike PrimeQ, does not handle n <= 0 and non-integer n.

meuPrimeQ[1] = False;
meuPrimeQ[2] = True;
meuPrimeQ[n_Integer /; n > 2] := Length[Divisors[n]] == 2

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