Theory of Finite Fields

examples/api/cpp/finite_field.cpp

 1/******************************************************************************
 2 * Top contributors (to current version):
 3 *   Alex Ozdemir
 4 *
 5 * This file is part of the cvc5 project.
 6 *
 7 * Copyright (c) 2009-2022 by the authors listed in the file AUTHORS
 8 * in the top-level source directory and their institutional affiliations.
 9 * All rights reserved.  See the file COPYING in the top-level source
10 * directory for licensing information.
11 * ****************************************************************************
12 *
13 * An example of solving finite field problems with cvc5's cpp API
14 */
15
16#include <cvc5/cvc5.h>
17
18#include <cassert>
19#include <iostream>
20
21using namespace std;
22using namespace cvc5;
23
24int main()
25{
26  Solver solver;
27  solver.setOption("produce-models", "true");
28
29  Sort f5 = solver.mkFiniteFieldSort("5");
30  Term a = solver.mkConst(f5, "a");
31  Term b = solver.mkConst(f5, "b");
32  Term z = solver.mkFiniteFieldElem("0", f5);
33
34  Term inv =
35      solver.mkTerm(EQUAL,
36                    {solver.mkTerm(FINITE_FIELD_ADD,
37                                   {solver.mkTerm(FINITE_FIELD_MULT, {a, b}),
38                                    solver.mkFiniteFieldElem("-1", f5)}),
39                     z});
40  Term aIsTwo = solver.mkTerm(
41      EQUAL,
42      {solver.mkTerm(FINITE_FIELD_ADD, {a, solver.mkFiniteFieldElem("-2", f5)}),
43       z});
44  // ab - 1 = 0
45  solver.assertFormula(inv);
46  // a = 2
47  solver.assertFormula(aIsTwo);
48
49  // should be SAT, with b = 2^(-1)
50  Result r = solver.checkSat();
51  assert(r.isSat());
52
53  cout << "a = " << solver.getValue(a) << endl;
54  cout << "b = " << solver.getValue(b) << endl;
55
56  // b = 2
57  Term bIsTwo = solver.mkTerm(
58      EQUAL,
59      {solver.mkTerm(FINITE_FIELD_ADD, {b, solver.mkFiniteFieldElem("-2", f5)}),
60       z});
61
62  // should be UNSAT, 2*2 - 1 != 0
63  solver.assertFormula(bIsTwo);
64
65  r = solver.checkSat();
66  assert(!r.isSat());
67}