Google OR-Tools中IntVar设Long.MAX_VALUE边界致模型无效问题问询
Great question—this is a common gotcha with OR-Tools' integer variable limits, not a mistake in your core logic. Here's a breakdown of what's happening:
The Root Cause
Google OR-Tools' CP-SAT solver relies on signed 64-bit integers for calculations, but it doesn’t allow variables to reach the absolute maximum value of a signed 64-bit integer (Long.MAX_VALUE = 9223372036854775807). This restriction exists because internal solver operations often require adding or manipulating values, which would cause an overflow if the variable is already at the maximum possible signed value.
The solver enforces a hard upper limit of Long.MAX_VALUE - 1 (9223372036854775806) for integer variables. When you set sumVar's upper bound to Long.MAX_VALUE, you exceed this limit, triggering the MODEL_INVALID status.
Simple Fixes
You have two solid options to resolve this:
- Stick with
Long.MAX_VALUE - 1as you already discovered—this keeps you within the solver's valid range. - Even better: Since you’re summing 3 boolean variables, the maximum possible value of
sumVaris 3. Setting the upper bound to 3 is far more efficient (it reduces the solver’s search space) and makes your model’s intent clearer, while avoiding the limit issue entirely.
Here’s the corrected code using the precise upper bound:
CpModel model = new CpModel(); IntVar[] var = new IntVar[3]; for (int i = 0; i < 3; i++) { var[i] = model.newBoolVar(String.format("var-%s", i)); } // Tight upper bound since sum of 3 bools can't exceed 3 IntVar sumVar = model.newIntVar(0, 3, "sum"); model.addEquality(sumVar, LinearExpr.sum(var)); CpSolver cp = new CpSolver(); CpSolverStatus st = cp.solve(model); System.out.println("solver status = " + st);
This will output FEASIBLE as expected, and it’s optimized for the solver to process quickly.
内容的提问来源于stack exchange,提问作者peru

