0
$\begingroup$

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

$\endgroup$
  • 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
2
$\begingroup$

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.

ClearAll[primeQ];
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]

True

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:

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

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

0.039507

12.245

5.72106

True

True

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

| improve this answer | |
$\endgroup$
2
$\begingroup$

@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
| improve this answer | |
$\endgroup$

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