# Length of a disjunction

Simple question: I'm trying to count the number of Roots to an equation. But both Length[x==1] and Length[x==1||x==2] return a value of 2. Length on longer expressions work fine. For example Length[x==1||x==2||x==5||x==5] returns 4 (which is what I want). It's just the case where I want the output of 1 that seems to be letting me down. What's the trick here to getting the right answer for x==1?

• What is x in your examples above? – bill s Aug 19 '15 at 1:18
• If x has not been assigned any numeric value then f[x_ == n_] := 1; f[Or[x__]] := Length[x]; followed by f[x == 1] or by f[x == 1 || x == 2 || x == 5 || x == 5] seems to give you what you want. Check that carefully for all the possible inputs you can give that. – Bill Aug 19 '15 at 1:38

The simple function, Count[#, _Equal, {0, -1}] & works well.

roots = x == 1 || x == 2 || x == 5 || x == 5; roots2 = x == 1 || x == 2; roots1 = x == 1;
Count[#, _Equal, {0, -1}] & /@ {roots, roots2, roots1}
(* {4, 2, 1} *)


Note that the third argument, {0, -1}, is necessary in order to obtain the correct answer for roots1.

A small function can do it.

roots = x == 1 || x == 2 || x == 5 || x == 5;
roots2 = x == 1 || x == 2;
roots1 = x == 1;

numRoots[expr_] :=
Module[{rootList = Apply[List, expr, {0, 1}], listDimensions},
listDimensions = Dimensions@rootList;
If[Dimensions@listDimensions == {1}, 1, First@listDimensions]
]

numRoots[#] & /@ {roots, roots2, roots1}
(* {4, 2, 1} *)


The function converts the head of expr (Or in this case) and the heads at level 1 (Equal in this case) to List [evaluate roots//FullForm]. This gives a nested list of the components of the disjunction. Dimension will now {2} from roots, {2, 2} for roots2, and {4, 2} for roots4. We just have to check how many entries are in the dimension list to return the number of roots.