# Count the number of sqrt and 4th powers in a function

This is a simple and short question. I have a function which contains a certain number of square roots and 4th powers, lets take this one:

f=Sqrt[x] Sqrt[y] Sqrt[z + 2] b^4 + c^3 + d^4


I want to be able to count the number of occurrences of the square roots (3) and the number of occurences of the 4th power (2). I think it should be possible to use Count for this, but I can't figure out how. I have tried

Count[f,_Sqrt,Infinity]


and

Count[f, Power[4, _], {0, Infinity}]


but both don't seem to work. Can someone tell me how to achieve this?

• Have a look at FullForm[f]; sqrt would be matched by Power[_, Rational[1, 2]] for instance. Jan 20, 2014 at 13:03
• As suggested by @b.gatessucks,you should check the FullForm of this expression first. Besides, patterns of specified types includes _Integer,_Real,_Complex,_List,_Symbol and the general _head, where head is returned by Head. So there is no _Sqrt but _Power,because Head[Sqrt[x]] returns Power. Jan 20, 2014 at 14:25

As the comments suggest, look at the FullForm and see what the pattern is that you need to match. For the requested patterns of Sqrt and 4th power, Rational[1, 2] and Power[__, 4] will do:

f = Sqrt[x] Sqrt[y] Sqrt[z + 2] b^4 + c^3 + d^4 + e^3;
Count[f, Power[__, Rational[1, 2]], Infinity]
Count[f, Power[__, 4], Infinity]


These give the expected counts 3 and 2. The Infinity option tells Count to look at all levels and the double slash __ matches any sequence of one or more characters (which will be raised to the designated power).

As Stefan points out, you could count the two patterns simultaneously

Count[f, Power[__, Rational[1, 2]] | Power[__, 4], Infinity]


to get a count of all the Sqrt's and the 4th powers (in this case 5). Thanks also to Szabolcs.

• why not Count[f, Power[, Rational[1, 2]] | Power[, 4], {0, Infinity}]? Jan 20, 2014 at 14:56
• Nice, thanks! A small follow-up: how does {0, Infinity} differ from just Infinity? Because if I use for example Count[Sec[x], Sec[__],..] mathematica returns 0 if I only use Infinity, but 1 if I use the {0,Infinity}' Jan 20, 2014 at 15:16
• @Michiel, {0,Infinity} looks at levels 0 to Infinity, while just Infinity looks at levels 1 to Infinity. I guess the choice is whether you expect to see anything in the Head. Jan 20, 2014 at 15:19
• @bills sorry did just realise, that the underscore etc. is formatted away. totally forgot that this is the case with comments. so mea culpa. Jan 20, 2014 at 17:42
• I agree with Stefan, the pattern should be Power[__, Rational[1, 2]]. What if you have f = Sqrt[x] Sqrt[y] Sqrt[z + 2] b^4 + c^3 + d^4 + e^3 + 1/2;`? Jan 20, 2014 at 17:57