5
$\begingroup$

For example, I tried to compile this function but Mathematica gives "The only function arguments supported are Times, Plus, or List", I have no a way to compile this.

isPrime = Compile[{{n, _Integer}},
  And @@ (Mod[n, #] != 0 & /@ Range[2, Sqrt@N@n])
  ]
$\endgroup$
  • $\begingroup$ You could use PrimeQ instead. $\endgroup$ – Michael E2 Jun 11 '13 at 19:27
  • 1
    $\begingroup$ You could rewrite it to a more procedural form, but in this case I don't see the point, you could instead use the fact that Mod is listable and look at ! MemberQ[Mod[n, Range[2, Sqrt@n]], 0] And use Divisible instead of checking result of Mod, or best use PrimeQ as Michael suggests $\endgroup$ – ssch Jun 11 '13 at 19:27
  • 3
    $\begingroup$ ...why not isPrime = Compile[{{n, _Integer}}, FreeQ[Mod[n, Range[2, Sqrt[n]]], 0]], if you insist on your approach? $\endgroup$ – J. M. will be back soon Jun 11 '13 at 19:30
2
$\begingroup$

To check whether the sentence is False or True, the And function is not appropriate, but FreeQ works best by J.M.:

isPrime = 
 Compile[{{n, _Integer}}, 
  And @@ (Mod[n, #] != 0 & /@ Range[2, Sqrt@N@n])]

Compile::cpapot: Compilation of And@@(n mod #1!=0&)/@Range[2,Sqrt[N[n]]] is not supported for the function argument And. The only function arguments supported are Times, Plus, or List. Evaluation will use the uncompiled function. >>

But:

isPrime = 
 Compile[{{n, _Integer}}, FreeQ[Mod[n, Range[2, Sqrt[n]]], 0]]

enter image description here

$\endgroup$

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.