Skip to content

Integer Knapsack


Given a set of items, determine how many items to put in the knapsack to maximize their summed value.


  • \(x_i\) is the number of items from each type.

  • \(v_i\) is the value of each item.

  • \(w_i\) is the weight of each item.

  • \(D\) is the range of \(x\).

Find \(x\) that maximizes the value: \(\begin{aligned} \max_{x_i \in D} \Sigma_i v_i x_i\\ \end{aligned}\)

and constrained by the weight: \(\begin{aligned} \Sigma_i w_i x_i = C \end{aligned}\)

Problem Versions

Binary Knapsack

Range: \(D = \{0, 1\}\)

Integer Knapsack

Range: \(D = [0, b]\)

Knapsack with integer variables and inequality constraint

Define the optimization problem

import numpy as np
import pyomo.environ as pyo

def define_knapsack_model(weights, values, max_weight, item_bound):
    model = pyo.ConcreteModel("knapsack")
    num_items = len(weights)

    model.x = pyo.Var(
        range(num_items), domain=pyo.NonNegativeIntegers, bounds=(0, item_bound)

    x_variables = np.array(list(model.x.values()))

    model.weight_constraint = pyo.Constraint(expr=x_variables @ weights <= max_weight)

    model.value = pyo.Objective(expr=x_variables @ values, sense=pyo.maximize)

    return model

Initialize the model with parameters

knapsack_model = define_knapsack_model(
    weights=[2, 3], values=[3, 5], max_weight=12, item_bound=3

Setting Up the Classiq Problem Instance

In order to solve the Pyomo model defined above, we use the Classiq combinatorial optimization engine. For the quantum part of the QAOA algorithm (QAOAConfig) - define the number of repetitions (num_layers):

from classiq import construct_combinatorial_optimization_model
from classiq.applications.combinatorial_optimization import OptimizerConfig, QAOAConfig

qaoa_config = QAOAConfig(num_layers=5, penalty_energy=20.0)

For the classical optimization part of the QAOA algorithm we define the maximum number of classical iterations (max_iteration) and the \(\alpha\)-parameter (alpha_cvar) for running CVaR-QAOA, an improved variation of the QAOA algorithm [3]:

optimizer_config = OptimizerConfig(max_iteration=60, alpha_cvar=0.7)

Lastly, we load the model, based on the problem and algorithm parameters, which we can use to solve the problem:

qmod = construct_combinatorial_optimization_model(

We also set the quantum backend we want to execute on:

from classiq import set_execution_preferences
from classiq.execution import ClassiqBackendPreferences, ExecutionPreferences

backend_preferences = ExecutionPreferences(

qmod = set_execution_preferences(qmod, backend_preferences)

Synthesizing the QAOA Circuit and Solving the Problem

We can now synthesize and view the QAOA circuit (ansatz) used to solve the optimization problem:

from classiq import write_qmod

write_qmod(qmod, "knapsack_integer")
from classiq import show, synthesize

qprog = synthesize(qmod)

We now solve the problem by calling the execute function on the quantum program we have generated:

from classiq import execute

res = execute(qprog).result()

We can check the convergence of the run:

from classiq.execution import VQESolverResult

vqe_result = res[0].value


Optimization Results

We can also examine the statistics of the algorithm:

import pandas as pd

from classiq.applications.combinatorial_optimization import (

solution = get_optimization_solution_from_pyo(
    knapsack_model, vqe_result=vqe_result, penalty_energy=qaoa_config.penalty_energy
optimization_result = pd.DataFrame.from_records(solution)
optimization_result.sort_values(by="cost", ascending=False).head(5)
probability cost solution count
38 0.008 19.0 [3, 2] 8
101 0.003 18.0 [1, 3] 3
74 0.004 16.0 [2, 2] 4
16 0.012 15.0 [0, 3] 12
7 0.017 14.0 [3, 1] 17

And the histogram:

optimization_result.hist("cost", weights=optimization_result["probability"])
array([[<Axes: title={'center': 'cost'}>]], dtype=object)


Lastly, we can compare to the classical solution of the problem:

from pyomo.opt import SolverFactory

solver = SolverFactory("couenne")

Model knapsack

    x : Size=2, Index=x_index
        Key : Lower : Value : Upper : Fixed : Stale : Domain
          0 :     0 :   3.0 :     3 : False : False : NonNegativeIntegers
          1 :     0 :   2.0 :     3 : False : False : NonNegativeIntegers

    value : Size=1, Index=None, Active=True
        Key  : Active : Value
        None :   True :  19.0

    weight_constraint : Size=1
        Key  : Lower : Body : Upper
        None :  None : 12.0 :  12.0