Here's one way to count the number of multiplications in an expression (equal to or greater than the number of Times
in the expression.) It should also work for several other binary operators. listable or not(, although I haven't tested it on them).
t[x_,oper_: Times]:=Tr@((Length[#]-1)&/@(Extract[x,{Sequence@@Drop[#,-1]}]&/@Position[x,oper]))
Usage
t[a b c + d e + f[a b] - 1/f[f[c d]]]
6
Under the hood.
Let's examine a b c + d e + f[a b] - 1/f[f[c d]]
, using Position
and Extract
and `TreeForm.
The tree structure of the expression...
ClearAll[a, b, c, d, e, f]
(x = a b c + d e + f[a b] - 1/f[f[c d]]) // TreeForm
Then the positions of the head, Times
.
Position[x, Times]
{{1, 0}, {2, 0}, {3, 1, 0}, {4, 0}, {4, 2, 1, 1, 1, 0}}
By dropping the final zero from each position we obtain the instances of Times
including the arguments.
Extract[x, {Sequence @@ Drop[#, -1]}] & /@ %
{a b c, d e, a b, -(1/f[f[c d]]), c d}
...the number of items.
Length[%]
5
[t[]
goes a step further to count the (arguments-1) for each Times
, namely, 6.]
...a look at the structure of each of those instances of Times.
TreeForm /@ %%