Hazem Abaza
Hazem Abaza

Reputation: 351

Solve for expression variables using Z3 in C++

How can I write equation that with 2 z3 expressions for example

z3::exp x;
Z3::exp y;

How can I get a linear equation in the form z3::exp Z= x+10*y

How can I solve for a expression variable using Z3 expresssions for example I have the following system of equations :

 x = a+b;
 a = 2*y;
 b = 4*c;

How can I get that x = 2*y + 4*c where x , y , b and c are all z3 expressions

Upvotes: 1

Views: 763

Answers (1)

alias
alias

Reputation: 30525

Something like this should work:

#include "z3++.h"

using namespace z3;

int main(void) {
    context ctx;
    expr x = ctx.int_const("x");
    expr y = ctx.int_const("y");
    expr a = ctx.int_const("a");
    expr b = ctx.int_const("b");
    expr c = ctx.int_const("c");
    solver s(ctx);

    s.add(x == a+b);
    s.add(a == 2*y);
    s.add(b == 4*c);
    s.add(x == 2*y + 4*c);

    std::cout << s.check() << "\n";
    model m = s.get_model();
    for (unsigned i = 0; i < m.size(); i++) {
        func_decl v = m[static_cast<int>(i)];
        std::cout << v.name() << " = " << m.get_const_interp(v) << "\n";
    }
    return 0;
}

Assuming you put this program in a file called a.cpp, You can compile and run it like this:

$ c++ a.cpp -lz3
$ ./a.out
sat
y = 0
c = 0
x = 0
b = 0
a = 0

The model you get is not particularly interesting because an all 0 assignment trivially satisfies it. But you can add other constraints and get more interesting values.

Upvotes: 1

Related Questions