4
$\begingroup$

What is the cause of this strange behavior of SquareFreeQ while PrimePowerQ works correctly:

Range[20] /. x_ /; SquareFreeQ[x] -> 0

0[0, 0, 0, 4, 0, 0, 0, 8, 9, 0, 0, 12, 0, 0, 0, 16, 0, 18, 0, 20]

Range[20] /. x_ /; PrimePowerQ[x] -> 0

{1, 0, 0, 0, 0, 6, 0, 0, 0, 10, 0, 12, 0, 14, 15, 0, 0, 18, 0, 20}

I use Mathematica 13.

$\endgroup$
2
  • 3
    $\begingroup$ Use x_Integer instead of x_. $\endgroup$
    – Alan
    Jun 4, 2022 at 0:14
  • 1
    $\begingroup$ Or use Replace[Range[20],x_ /; SquareFreeQ[x] -> 0,1]. As others have noted, ReplaceAll looks at (and may be used to replace) the Head of the expression. Compare Range[2] /. x_ /; SquareFreeQ[x] -> f[x], giving f[List][f[1], f[2]] with Replace[Range[2],x_ /; SquareFreeQ[x] -> f[x],1], giving {f[1], f[2]} $\endgroup$
    – user1066
    Jun 4, 2022 at 6:41

2 Answers 2

7
$\begingroup$

Try to evaluate this: SquareFreeQ[List]

It turns out that List is, indeed, square-free. So, it was replaced (it was the head of the expression, so that's where the 0 was placed).

On the other hand, PrimePowerQ[List] is False, so the head List was not replaced.

$\endgroup$
4
$\begingroup$

Try this:

Thread[SquareFreeQ[Range[20]]
(*{True, True, True, False, True, True, True, False, False, True, True, False, True, True, True, False, True, False, True, False}*)

PrimePowerQ[Range[20]]
(*{False, True, True, True, True, False, True, True, True, False, True, False, True, False, False, True, True, False, True, False}*)

And you can apply Alan's suggestion:

Range[20] /. x_Integer /; SquareFreeQ[x] -> 0
(*{0, 0, 0, 4, 0, 0, 0, 8, 9, 0, 0, 12, 0, 0, 0, 16, 0, 18, 0, 20}*)

Range[20] /. x_Integer /; PrimePowerQ[x] -> 0
(*{1, 0, 0, 0, 0, 6, 0, 0, 0, 10, 0, 12, 0, 14, 15, 0, 0, 18, 0, 20}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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