# How can I compile function with Apply?

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

• You could use PrimeQ instead. – Michael E2 Jun 11 '13 at 19:27
• 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 – ssch Jun 11 '13 at 19:27
• ...why not isPrime = Compile[{{n, _Integer}}, FreeQ[Mod[n, Range[2, Sqrt[n]]], 0]], if you insist on your approach? – J. M.'s ennui Jun 11 '13 at 19:30

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]]