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 = solver.mkTerm(
35      Kind::EQUAL,
36      {solver.mkTerm(Kind::FINITE_FIELD_ADD,
37                     {solver.mkTerm(Kind::FINITE_FIELD_MULT, {a, b}),
38                      solver.mkFiniteFieldElem("-1", f5)}),
39       z});
40  Term aIsTwo =
41      solver.mkTerm(Kind::EQUAL,
42                    {solver.mkTerm(Kind::FINITE_FIELD_ADD,
43                                   {a, solver.mkFiniteFieldElem("-2", f5)}),
44                     z});
45  // ab - 1 = 0
46  solver.assertFormula(inv);
47  // a = 2
48  solver.assertFormula(aIsTwo);
49
50  // should be SAT, with b = 2^(-1)
51  Result r = solver.checkSat();
52  assert(r.isSat());
53
54  cout << "a = " << solver.getValue(a) << endl;
55  cout << "b = " << solver.getValue(b) << endl;
56
57  // b = 2
58  Term bIsTwo =
59      solver.mkTerm(Kind::EQUAL,
60                    {solver.mkTerm(Kind::FINITE_FIELD_ADD,
61                                   {b, solver.mkFiniteFieldElem("-2", f5)}),
62                     z});
63
64  // should be UNSAT, 2*2 - 1 != 0
65  solver.assertFormula(bIsTwo);
66
67  r = solver.checkSat();
68  assert(!r.isSat());
69}