# Strange behavior of 'SquareFreeQ'

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.

• Use x_Integer instead of x_.
– Alan
Jun 4, 2022 at 0:14
• 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]} Jun 4, 2022 at 6:41

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.

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}*)

list = Range[10];


Two positional solutions

p = Position[list, _?SquareFreeQ, Heads -> False]


{{1}, {2}, {3}, {5}, {6}, {7}, {10}}

Using ReplaceAt (new in 13.1)

ReplaceAt[_ :> 0, p] @ list


{0, 0, 0, 4, 0, 0, 0, 8, 9, 0}

Using MapAt

MapAt[0 &, p] @ list


{0, 0, 0, 4, 0, 0, 0, 8, 9, 0}