diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md
index 8a3ed02c4..2eef1a2b5 100644
--- a/BREAKING-CHANGES.md
+++ b/BREAKING-CHANGES.md
@@ -913,11 +913,18 @@ where `P` is not decided, so a count is a sum of brackets: `sum(iverson(k divide
([#1478](https://github.com/asc-community/AngouriMath/issues/1478)). In 2.5.0 the name was read as a
variable multiplying its argument, and a product with a truth value is `NaN`.
+A sum of a bracket is counted in closed form, however long the range, where the statement bounds the
+index, fixes it at a point, fixes its residue or makes it a perfect power, with `not` and `or` counted by inclusion and
+exclusion: the number of whole numbers from `L` to `U` in the class `r` modulo `m` is
+`floor((U - r)/m) - floor((L - 1 - r)/m)`, and never below zero.
+
| Input | Was (2.5.0) | Now |
|---|---|---|
| `"iverson(2 > 1)".ToEntity().Simplify()` | `NaN` — `iverson * (2 > 1)` | `1` |
| `"iverson(x > 0)".ToEntity().Simplify()` | `iverson * (x > 0)` | `iverson(x > 0)` |
| `"sum(sum(sum(iverson(r + b + g = 4), g, 0, 3), b, 0, 3), r, 0, 3)".ToEntity().Simplify()` | `NaN` | `12` |
+| `"sum(iverson(2 divides k or 3 divides k), k, 1, 1000)".ToEntity().Simplify()` | `sum(iverson * (2 divides k or 3 divides k), k, 1, 1000)` | `667` |
+| `"sum(sum(sum(iverson(a + b + c = 20), c, 0, 20), b, 0, 20), a, 0, 20)".ToEntity().Simplify()` | did not finish in two minutes | `231` |
### A statement about a sum up to `n` is decided by induction
diff --git a/Sources/.editorconfig b/Sources/.editorconfig
index d19f61600..9ff5ed08e 100644
--- a/Sources/.editorconfig
+++ b/Sources/.editorconfig
@@ -431,6 +431,9 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed
[AngouriMath/Functions/Algebra/Polynomials/FactorialSum.cs]
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
+[AngouriMath/Functions/Algebra/Polynomials/IversonSum.cs]
+file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
+
[Tests/UnitTests/Core/FactorialSumTest.cs]
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
[Tests/UnitTests/Core/ClosedFormProductTest.cs]
diff --git a/Sources/AngouriMath/Docs/Usage/Syntax.md b/Sources/AngouriMath/Docs/Usage/Syntax.md
index 3441dcc2a..c08f22fb6 100644
--- a/Sources/AngouriMath/Docs/Usage/Syntax.md
+++ b/Sources/AngouriMath/Docs/Usage/Syntax.md
@@ -278,7 +278,11 @@ identities of chapter 8 of Sullivan and Mackey's *An Introduction to Proofs*, so
**Iverson bracket** — `iverson(P)`. `1` where the statement `P` holds and `0` where it does not,
which is how a count is written as a sum: `sum(iverson(k divides 12), k, 1, 12)` is `6`, the number
of divisors of `12`. A statement that is not decided keeps the node, which prints as `[\![P]\!]` in
-LaTeX, and so does a number, which is not a statement.
+LaTeX, and so does a number, which is not a statement. A sum of a bracket whose statement bounds the
+index, fixes it, fixes its residue or makes it a perfect power is counted in closed form, however long the range, with `not`
+and `or` counted by inclusion and exclusion: `sum(iverson(2 divides k or 3 divides k), k, 1, 1000)`
+is `667`, and `sum(iverson(not 2 divides k and not 5 divides k), k, 1, n)` is
+`n - floor(n/2) - floor(n/5) + floor(n/10)` for a whole `n >= 0`.
**Error functions** — `erf(z)` `erfc(z)` `erfi(z)`. The error function
`2/sqrt(pi) int_0^z e^(-t^2) dt`, its complement `1 - erf(z)`, and the imaginary error function
diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/IversonSum.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/IversonSum.cs
new file mode 100644
index 000000000..e264c87fe
--- /dev/null
+++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/IversonSum.cs
@@ -0,0 +1,420 @@
+//
+// Copyright (c) 2019-2026 Angouri.
+// AngouriMath is licensed under MIT.
+// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
+// Website: https://am.angouri.org.
+//
+
+using System.Collections.Generic;
+using PeterO.Numbers;
+using static AngouriMath.Entity;
+using static AngouriMath.Entity.Number;
+
+namespace AngouriMath.Functions
+{
+ ///
+ /// A sum of an Iverson bracket over a range of whole numbers is a count, written in closed
+ /// form: how many whole numbers of the range satisfy the statement. A product of brackets is
+ /// the bracket of the conjunction.
+ /// sum(iverson(2 divides k or 3 divides k), k, 1, 1000) is 667.
+ ///
+ ///
+ ///
+ /// The statement is read as conditions on the index. An equation linear in it fixes it at a
+ /// point p, and then the sum is a bracket again, of p being whole, in the range,
+ /// and satisfying the other conditions: in a nested sum that is what the next sum out counts.
+ /// A comparison linear in the index, with a numeric slope, bounds it from one side, and so
+ /// does a membership in an interval. A divisibility of a linear function of the index with
+ /// whole coefficients fixes its residue, and several residues combine into one class or
+ /// none, by the Chinese remainder theorem. A conjunct that does not mention the index is a
+ /// factor, and so is a linear function of it being whole, which depends only on its constant
+ /// term. What is left is the number of whole numbers from L to U in the class
+ /// r modulo m, floor((U - r)/m) - floor((L - 1 - r)/m), or
+ /// U - L + 1 with no class, and never below zero, which is also the count of an empty
+ /// range. A bound that is not a number is read as real, as a bound of the range that is not a
+ /// number is read as whole.
+ ///
+ ///
+ /// A negation and a disjunction are counted by inclusion and exclusion: not Q counts
+ /// the range less Q, and Q or R counts Q and R less both. So
+ /// sum(iverson(not 2 divides k and not 5 divides k), k, 1, 99) is 40, Sullivan and
+ /// Mackey's §8.7.4 Try 1.
+ ///
+ /// https://github.com/asc-community/AngouriMath/issues/1409
+ /// https://github.com/asc-community/AngouriMath/issues/1478
+ ///
+ internal static class IversonSum
+ {
+ // Each negation and disjunction doubles the counts taken; past this many the sum is declined.
+ private const int MaxCounts = 64;
+
+ // Residue classes are combined by stepping through one modulus, so a larger one is declined.
+ private const int MaxModulus = 1 << 16;
+
+ // A perfect power's exponent past this is declined; the least common multiple grows fast.
+ private const int MaxPowerExponent = 1 << 10;
+
+ ///
+ /// sum(c iverson(P), index, from, to) as a count, for a c free of the index,
+ /// or .
+ ///
+ internal static Entity? ClosedForm(Entity expression, Entity var, Entity from, Entity to)
+ {
+ if (var is not Variable index)
+ return null;
+ if (!PolynomialSummation.IsWholeOrSymbolic(from) || !PolynomialSummation.IsWholeOrSymbolic(to)
+ || from.ContainsNode(index) || to.ContainsNode(index))
+ return null;
+ if (Read(expression, index, from, to) is { } count)
+ return count;
+ // A sum of a bracket inside is counted first, in terms of this index, and where that
+ // count is a bracket again it is counted here. Only a sum with a bracket in it is
+ // simplified for this: any other would be written out with this index a symbol.
+ if (expression is Summationf && ContainsABracket(expression)
+ && expression.InnerSimplified is var inner && !ReferenceEquals(inner, expression))
+ return Read(inner, index, from, to);
+ return null;
+ }
+
+ private static bool ContainsABracket(Entity expression)
+ {
+ foreach (var node in expression.Nodes)
+ if (node is Iversonf)
+ return true;
+ return false;
+ }
+
+ private static Entity? Read(Entity expression, Variable index, Entity from, Entity to)
+ {
+ // A product of brackets is the bracket of the conjunction.
+ var statements = new List();
+ Entity coefficient = Integer.One;
+ foreach (var factor in Mulf.LinearChildren(expression))
+ {
+ if (factor is Iversonf bracket && bracket.Argument.ContainsNode(index))
+ statements.Add(bracket.Argument);
+ else if (factor.ContainsNode(index))
+ return null;
+ else
+ coefficient *= factor;
+ }
+ if (statements.Count == 0)
+ return null;
+ var budget = MaxCounts;
+ if (Count(statements, index, from, to, ref budget) is not { } count)
+ return null;
+ return (coefficient * count).InnerSimplified;
+ }
+
+ ///
+ /// The number of whole from to
+ /// that satisfy every one of , or
+ /// .
+ ///
+ private static Entity? Count(List conjuncts, Variable k, Entity from, Entity to, ref int budget)
+ {
+ if (--budget < 0)
+ return null;
+ var atoms = new List();
+ foreach (var conjunct in conjuncts)
+ Flatten(conjunct, atoms);
+
+ // A negation or a disjunction is split first, by inclusion and exclusion over the rest.
+ for (var i = 0; i < atoms.Count; i++)
+ {
+ if (!atoms[i].ContainsNode(k))
+ continue;
+ if (atoms[i] is Notf(var negated))
+ {
+ var rest = Without(atoms, i);
+ if (Count(rest, k, from, to, ref budget) is not { } all)
+ return null;
+ rest.Add(negated);
+ if (Count(rest, k, from, to, ref budget) is not { } negatedCount)
+ return null;
+ return all - negatedCount;
+ }
+ if (atoms[i] is Orf(var either, var other))
+ {
+ var withLeft = Without(atoms, i);
+ var withRight = Without(atoms, i);
+ var withBoth = Without(atoms, i);
+ withLeft.Add(either);
+ withRight.Add(other);
+ withBoth.Add(either);
+ withBoth.Add(other);
+ if (Count(withLeft, k, from, to, ref budget) is not { } left
+ || Count(withRight, k, from, to, ref budget) is not { } right
+ || Count(withBoth, k, from, to, ref budget) is not { } both)
+ return null;
+ return left + right - both;
+ }
+ }
+
+ // An equation fixes the index: the sum of [k = p and Q(k)] is [p whole, in the range,
+ // and Q(p)], a bracket again, which is what lets a sum outside count it in turn.
+ for (var i = 0; i < atoms.Count; i++)
+ {
+ if (atoms[i] is not Equalsf(var equationLeft, var equationRight) || !atoms[i].ContainsNode(k)
+ || Root(equationLeft - equationRight, k) is not { } point)
+ continue;
+ Entity condition = (from <= point) & (point <= to);
+ if (point.Evaled is not Integer)
+ condition = point.In(MathS.Sets.Z) & condition;
+ for (var j = 0; j < atoms.Count; j++)
+ if (j != i)
+ condition &= atoms[j].Substitute(k, point);
+ return MathS.Iverson(condition);
+ }
+
+ var lower = new List { from };
+ var upper = new List { to };
+ var factors = new List();
+ var residue = EInteger.Zero;
+ var modulus = EInteger.One;
+ // k = m^e for some whole m, where every such condition's e divides this one.
+ var powerExponent = 0;
+ foreach (var atom in atoms)
+ {
+ if (!atom.ContainsNode(k))
+ {
+ factors.Add(atom);
+ continue;
+ }
+ switch (atom)
+ {
+ case Dividesf(var divisor, var dividend):
+ if (Residue(divisor, dividend, k) is not { } residueClass)
+ return null;
+ if (residueClass.Modulus.IsZero)
+ return Integer.Zero;
+ if (Combined(residue, modulus, residueClass.Residue, residueClass.Modulus) is not { } combinedClass)
+ return null;
+ if (combinedClass.Modulus.IsZero)
+ return Integer.Zero;
+ (residue, modulus) = (combinedClass.Residue, combinedClass.Modulus);
+ break;
+ // k is a perfect e-th power: counted by the root of each end, over a range of
+ // positive whole numbers, and two such conditions are the power of the least
+ // common multiple -- a square that is a cube is a sixth power.
+ case Existsf(var root, var over, var body) when PowerExponent(root, over, body, k) is { } exponent:
+ powerExponent = powerExponent == 0 ? exponent : Lcm(powerExponent, exponent);
+ if (powerExponent > MaxPowerExponent)
+ return null;
+ break;
+ // s k + c is whole for a whole k exactly where c is, s being whole.
+ case Set.Inf(var element, Set.SpecialSet.Integers):
+ if (!TreeAnalyzer.TryGetPolyLinear(element.InnerSimplified, k, out var memberSlope, out var memberConstant)
+ || memberConstant.ContainsNode(k) || memberSlope.Evaled is not Integer)
+ return null;
+ factors.Add(memberConstant.In(MathS.Sets.Z));
+ break;
+ case Greaterf or GreaterOrEqualf or Lessf or LessOrEqualf:
+ if (atom is not IBinaryNode { NodeFirstChild: var lhs, NodeSecondChild: var rhs })
+ return null;
+ if (!TreeAnalyzer.TryGetPolyLinear((lhs - rhs).InnerSimplified, k, out var slopeEntity, out var intercept)
+ || intercept.ContainsNode(k) || slopeEntity.Evaled is not Real slope || slope.IsZero)
+ return null;
+ // a k + b compared with 0: the point where it is 0, and which side of it holds.
+ var bound = (-intercept / slopeEntity).InnerSimplified;
+ // Off the real line the comparison has no truth value, and neither has the sum.
+ if (bound.Evaled is Complex boundValue && !boundValue.ImaginaryPart.IsZero)
+ return null;
+ var rising = slope.IsPositive;
+ switch (atom)
+ {
+ case Greaterf:
+ if (rising) lower.Add(MathS.Floor(bound) + 1); else upper.Add(MathS.Ceil(bound) - 1);
+ break;
+ case GreaterOrEqualf:
+ if (rising) lower.Add(MathS.Ceil(bound)); else upper.Add(MathS.Floor(bound));
+ break;
+ case Lessf:
+ if (rising) upper.Add(MathS.Ceil(bound) - 1); else lower.Add(MathS.Floor(bound) + 1);
+ break;
+ default:
+ if (rising) upper.Add(MathS.Floor(bound)); else lower.Add(MathS.Ceil(bound));
+ break;
+ }
+ break;
+ default:
+ return null;
+ }
+ }
+
+ Entity least = lower[0], greatest = upper[0];
+ for (var i = 1; i < lower.Count; i++)
+ least = MathS.Max(least, lower[i]);
+ for (var i = 1; i < upper.Count; i++)
+ greatest = MathS.Min(greatest, upper[i]);
+ Entity count;
+ if (powerExponent > 0)
+ {
+ // The powers of the positive whole numbers up to U are floor(U^(1/e)) many; below
+ // 1 the powers of zero and of negative numbers would enter, so the range starts
+ // there, and a residue class on top of a power is not counted here.
+ if (!modulus.Equals(EInteger.One) || from.Evaled is not Integer { EInteger.Sign: > 0 })
+ return null;
+ count = RootFloor(greatest, powerExponent) - RootFloor(least - 1, powerExponent);
+ }
+ else
+ count = modulus.Equals(EInteger.One)
+ ? greatest - least + 1
+ : MathS.Floor((greatest - Integer.Create(residue)) / Integer.Create(modulus))
+ - MathS.Floor((least - 1 - Integer.Create(residue)) / Integer.Create(modulus));
+ count = MathS.Max(0, count);
+ if (factors.Count > 0)
+ {
+ var condition = factors[0];
+ for (var i = 1; i < factors.Count; i++)
+ condition &= factors[i];
+ count = MathS.Iverson(condition) * count;
+ }
+ return count;
+ }
+
+ ///
+ /// The conjuncts of a statement, with a membership in an interval written as the two
+ /// comparisons it is.
+ ///
+ private static void Flatten(Entity statement, List into)
+ {
+ switch (statement)
+ {
+ case Andf(var left, var right):
+ Flatten(left, into);
+ Flatten(right, into);
+ break;
+ case Set.Inf(var element, Set.Interval interval):
+ if (interval.Left is not Real { IsFinite: false })
+ into.Add(interval.LeftClosed ? interval.Left <= element : interval.Left < element);
+ if (interval.Right is not Real { IsFinite: false })
+ into.Add(interval.RightClosed ? element <= interval.Right : element < interval.Right);
+ break;
+ default:
+ into.Add(statement);
+ break;
+ }
+ }
+
+ private static List Without(List atoms, int at)
+ {
+ var rest = new List(atoms.Count);
+ for (var i = 0; i < atoms.Count; i++)
+ if (i != at)
+ rest.Add(atoms[i]);
+ return rest;
+ }
+
+ ///
+ /// Where a function linear in with a real numeric slope is zero, or
+ /// : the point an equation fixes the index at.
+ ///
+ private static Entity? Root(Entity difference, Variable k)
+ {
+ if (!TreeAnalyzer.TryGetPolyLinear(difference.InnerSimplified, k, out var slope, out var constant)
+ || constant.ContainsNode(k) || slope.Evaled is not Real { IsZero: false })
+ return null;
+ var root = (-constant / slope).InnerSimplified;
+ return root.Evaled is Complex rootValue && !rootValue.ImaginaryPart.IsZero ? null : root;
+ }
+
+ ///
+ /// e where exists m in S : m^e = k says that is a
+ /// perfect e-th power, for S the positive, the non-negative or all whole
+ /// numbers, or . Over a range of positive whole numbers the three
+ /// agree: zero is out of it, and so is every odd power of a negative number.
+ ///
+ private static int? PowerExponent(Entity root, Entity over, Entity body, Variable k)
+ {
+ if (root is not Variable m || m == k
+ || over is not (Set.SpecialSet.PositiveIntegers or Set.SpecialSet.NonNegativeIntegers or Set.SpecialSet.Integers))
+ return null;
+ var power = body switch
+ {
+ Equalsf(Powf(var powerBase, var powerExponent), var target) when powerBase == m && target == k => powerExponent,
+ Equalsf(var target, Powf(var powerBase, var powerExponent)) when powerBase == m && target == k => powerExponent,
+ _ => null,
+ };
+ return power?.Evaled is Integer { EInteger: var e } && e.CompareTo(EInteger.FromInt32(2)) >= 0 && e.CanFitInInt32()
+ ? e.ToInt32Checked()
+ : null;
+ }
+
+ private static int Lcm(int a, int b)
+ {
+ int x = a, y = b;
+ while (y != 0)
+ (x, y) = (y, x % y);
+ return a / x * b;
+ }
+
+ ///
+ /// The number of positive whole m with m^e at most :
+ /// computed exactly where the bound is a number, and floor(bound^(1/e)) where not.
+ ///
+ private static Entity RootFloor(Entity bound, int e)
+ {
+ if (bound.Evaled is not Integer { EInteger: var value })
+ return MathS.Floor(MathS.Pow(bound, Rational.Create(1, e)));
+ if (value.Sign <= 0)
+ return Integer.Zero;
+ // The largest m with m^e <= value, by bisection between 0 and 2^(bits/e + 1).
+ var low = EInteger.Zero;
+ var high = EInteger.One.ShiftLeft((int)(value.GetUnsignedBitLengthAsInt64() / e) + 1);
+ while (low.CompareTo(high) < 0)
+ {
+ var middle = low.Add(high).Add(EInteger.One).ShiftRight(1);
+ if (middle.Pow(e).CompareTo(value) <= 0)
+ low = middle;
+ else
+ high = middle.Subtract(EInteger.One);
+ }
+ return Integer.Create(low);
+ }
+
+ ///
+ /// The class of whole for which a whole
+ /// divides s k + e, with s and e whole: a residue and a modulus, the
+ /// modulus zero where no k does, or .
+ ///
+ private static (EInteger Residue, EInteger Modulus)? Residue(Entity divisor, Entity dividend, Variable k)
+ {
+ if (divisor.ContainsNode(k) || divisor.Evaled is not Integer { IsZero: false } d)
+ return null;
+ if (!TreeAnalyzer.TryGetPolyLinear(dividend.InnerSimplified, k, out var slopeEntity, out var interceptEntity)
+ || slopeEntity.Evaled is not Integer s || interceptEntity.Evaled is not Integer e)
+ return null;
+ var m = d.EInteger.Abs();
+ if (m.CompareTo(EInteger.FromInt32(MaxModulus)) > 0)
+ return null;
+ // s k + e = 0 mod m: solvable where g = gcd(s, m) divides e, and then k is one class
+ // modulo m / g, found by trying its members.
+ var g = s.EInteger.Gcd(m);
+ if (!e.EInteger.Remainder(g).IsZero)
+ return (EInteger.Zero, EInteger.Zero);
+ var classModulus = m.Divide(g);
+ for (var r = EInteger.Zero; r.CompareTo(classModulus) < 0; r = r.Add(EInteger.One))
+ if (s.EInteger.Multiply(r).Add(e.EInteger).Mod(m).IsZero)
+ return (r, classModulus);
+ return (EInteger.Zero, EInteger.Zero);
+ }
+
+ ///
+ /// The class that is modulo and
+ /// modulo at once, the modulus zero where the two
+ /// are disjoint, or where the combined modulus is too large to step
+ /// through.
+ ///
+ private static (EInteger Residue, EInteger Modulus)? Combined(EInteger r1, EInteger m1, EInteger r2, EInteger m2)
+ {
+ var combined = m1.Divide(m1.Gcd(m2)).Multiply(m2);
+ if (combined.CompareTo(EInteger.FromInt32(MaxModulus)) > 0)
+ return null;
+ for (var t = r1; t.CompareTo(combined) < 0; t = t.Add(m1))
+ if (t.Subtract(r2).Mod(m2).IsZero)
+ return (t, combined);
+ return (EInteger.Zero, EInteger.Zero);
+ }
+ }
+}
diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Calculus.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Calculus.Classes.cs
index e78c84687..dba589426 100644
--- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Calculus.Classes.cs
+++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Calculus.Classes.cs
@@ -232,9 +232,14 @@ public partial record Summationf
/// reaches is the two cases the expansion declines: a symbolic bound, and a concrete
/// range too long to write out — where it is not a fallback but the better answer,
/// since it computes rather than expands.
+ ///
+ /// A count comes before all of them: a sum of an Iverson bracket is the number of
+ /// indices its statement holds for, which is computed however long the range is, and in
+ /// a nested sum the count of the inner one is what the outer one sums.
///
protected override Entity InnerSimplify(bool isExact) =>
- Expanded(this, Expression, Var, From, To, static (a, b) => a + b, 0, isExact)
+ Functions.IversonSum.ClosedForm(Expression, Var, From, To)
+ ?? Expanded(this, Expression, Var, From, To, static (a, b) => a + b, 0, isExact)
?? Functions.PolynomialSummation.ClosedForm(Expression, Var, From, To)
?? Functions.ExponentialSeries.ClosedForm(Expression, Var, From, To)
?? Functions.BinomialSum.ClosedForm(Expression, Var, From, To)
diff --git a/Sources/Tests/UnitTests/Convenience/IversonTest.cs b/Sources/Tests/UnitTests/Convenience/IversonTest.cs
index da24e004e..b33bfdbaf 100644
--- a/Sources/Tests/UnitTests/Convenience/IversonTest.cs
+++ b/Sources/Tests/UnitTests/Convenience/IversonTest.cs
@@ -70,6 +70,105 @@ public void SubstitutingDecidesIt()
public void ACountIsASumOfBrackets(string input, string expected)
=> Assert.Equal(expected.ToEntity(), input.ToEntity().Simplify());
+ ///
+ /// A sum of a bracket is a count, computed in closed form however long the range: the
+ /// whole numbers of an interval, and the members of a residue class, with a negation and a
+ /// disjunction counted by inclusion and exclusion.
+ ///
+ [Theory]
+ [InlineData("sum(iverson(k >= 3), k, 1, 10)", "8")]
+ [InlineData("sum(iverson(k > 5/2 and k < 7), k, 1, 10)", "4")]
+ [InlineData("sum(iverson(2 k + 1 <= 11), k, 0, 1000)", "6")]
+ [InlineData("sum(iverson(k = 7/2), k, 0, 10)", "0")]
+ [InlineData("sum(iverson(k = 4), k, 0, 3)", "0")]
+ [InlineData("sum(iverson(2 divides k), k, 1, 1000)", "500")]
+ [InlineData("sum(iverson(2 divides k or 3 divides k), k, 1, 1000)", "667")]
+ [InlineData("sum(iverson(3 divides 2 k + 1), k, 0, 99)", "33")]
+ [InlineData("sum(iverson(2 divides k and 3 divides k + 1), k, 0, 59)", "10")]
+ [InlineData("sum(iverson(2 divides k and 2 divides k + 1), k, 0, 99)", "0")]
+ [InlineData("sum(iverson(k in [2; 5]), k, 0, 10)", "4")]
+ [InlineData("sum(iverson(k in (2; +oo)), k, 0, 10)", "8")]
+ [InlineData("sum(iverson(k + 1/2 in ZZ), k, 0, 9)", "0")]
+ [InlineData("sum(iverson(k = 3 and 3 divides 12), k, 0, 9)", "1")]
+ // Sullivan and Mackey's §8.7.4 Try 1: the numbers below 100 that are multiples of neither
+ // 2 nor 5.
+ [InlineData("sum(iverson(not 2 divides k and not 5 divides k), k, 1, 99)", "40")]
+ // A perfect power is counted by the roots of the ends, and powers of two exponents are
+ // the powers of their least common multiple. Ex 8.7.5: the numbers up to 1000 that are
+ // not squares, cubes or fourth powers; §8.7.4 Try 2: below 1000, neither squares, cubes
+ // nor fifth powers.
+ [InlineData("sum(iverson(exists m in ZZ : m^2 = k), k, 1, 1000)", "31")]
+ [InlineData("sum(iverson((exists m in ZZ+ : m^2 = k) and (exists m in ZZ+ : m^3 = k)), k, 1, 1000)", "3")]
+ [InlineData("sum(iverson(not (exists m in ZZ+ : m^2 = k) and not (exists m in ZZ+ : m^3 = k) and not (exists m in ZZ+ : m^4 = k)), k, 1, 1000)", "962")]
+ [InlineData("sum(iverson(not (exists m in ZZ+ : m^2 = k) and not (exists m in ZZ+ : m^3 = k) and not (exists m in ZZ+ : m^5 = k)), k, 1, 999)", "960")]
+ // Ex 8.5.3: 20 identical coins among three pirates, binomial(22, 2) ways.
+ [InlineData("sum(sum(sum(iverson(a + b + c = 20), c, 0, 20), b, 0, 20), a, 0, 20)", "231")]
+ public void ACountIsComputedInClosedForm(string input, string expected)
+ => Assert.Equal(expected.ToEntity(), input.ToEntity().Simplify());
+
+ ///
+ /// A symbolic range is counted with floors, by inclusion and exclusion:
+ /// n - floor(n/2) - floor(n/5) + floor(n/10), and nothing below an empty range.
+ ///
+ [Theory]
+ [InlineData(99, 40)]
+ [InlineData(1000, 400)]
+ [InlineData(10, 4)]
+ [InlineData(0, 0)]
+ [InlineData(-5, 0)]
+ public void ASymbolicRangeIsCountedWithFloors(int n, int expected)
+ {
+ var count = "sum(iverson(not 2 divides k and not 5 divides k), k, 1, n)".ToEntity().Simplify();
+ Assert.DoesNotContain(count.Nodes, node => node is Entity.Summationf);
+ Assert.Equal(Entity.Number.Integer.Create(expected), count.Substitute("n", n).Simplify());
+ }
+
+ ///
+ /// A sum over an index an equation fixes is a bracket of the point, so a nested sum is
+ /// counted from the inside with the outer index a symbol: for each r, the triples
+ /// of Ex 8.3.18 with that many red balls.
+ ///
+ [Theory]
+ [InlineData("0", "3")]
+ [InlineData("1", "4")]
+ [InlineData("3", "2")]
+ [InlineData("5", "0")]
+ [InlineData("1/2", "0")]
+ public void ANestedSumIsCountedFromTheInside(string r, string expected)
+ {
+ var count = "sum(sum(iverson(r + b + g = 4), g, 0, 3), b, 0, 3)".ToEntity().Simplify();
+ Assert.DoesNotContain(count.Nodes, node => node is Entity.Summationf);
+ Assert.Equal(expected.ToEntity(), count.Substitute("r", r.ToEntity()).Simplify());
+ }
+
+ ///
+ /// Whether a linear function of the index is whole depends only on its constant term.
+ ///
+ [Theory]
+ [InlineData("3", "5")]
+ [InlineData("1/3", "0")]
+ public void WholenessOfALinearFunctionIsAFactor(string m, string expected)
+ {
+ var count = "sum(iverson(k + m in ZZ), k, 1, 5)".ToEntity().Simplify();
+ Assert.DoesNotContain(count.Nodes, node => node is Entity.Summationf);
+ Assert.Equal(expected.ToEntity(), count.Substitute("m", m.ToEntity()).Simplify());
+ }
+
+ ///
+ /// A point counts once where it is whole and in the range, and a point that is not a
+ /// number says so with a bracket of its own.
+ ///
+ [Theory]
+ [InlineData("5", "1")]
+ [InlineData("11", "0")]
+ [InlineData("5/2", "0")]
+ public void ASymbolicPointCountsWhereItIsWholeAndInRange(string m, string expected)
+ {
+ var count = "sum(iverson(k = m), k, 1, 10)".ToEntity().Simplify();
+ Assert.DoesNotContain(count.Nodes, node => node is Entity.Summationf);
+ Assert.Equal(expected.ToEntity(), count.Substitute("m", m.ToEntity()).Simplify());
+ }
+
[Theory]
[InlineData("iverson(x > 0)", "iverson(x > 0)")]
[InlineData("iverson(n divides 12) + 1", "iverson(n divides 12) + 1")]