Search code examples
pythonz3smtsat

Z3 Python Mod Int Issue


I want to print primes below 20 using Z3. The following program prints 2, 3, 5, and 7, but not 11, 13, 17, or 19.

Any idea what is wrong although isPrime(11), isPrime(13), isPrime(17), or isPrime(19) are all satisfied in my testing.

from z3 import *
def isPrime(x):
    y = Int('y')
    return And(x > 1, Not(Exists(y, And(y < x, 1 < y, x % y == 0))))

s = Solver()

x = Int('x')
s.add(isPrime(x))
s.add(x < 20)

while s.check() == sat:
    ans = s.model()[x]
    print(ans)
    s.add(x != ans)

Solution

  • Using z3 version 4.10.2, your program works just fine for me, outputting:

    2
    3
    19
    5
    17
    11
    7
    13
    

    which are all the primes below 20.

    Perhaps you have different version installed?

    Note that z3 (or any other SMT solver) will not be effective in finding primes in general, for large-primes. But for this problem, its bounded size makes it possible to solve the problem in full. However, I wouldn't be surprised if this changed in the next release, or even with the next build: These sorts of problems are just not suitable for solving with an SMT solver; and you'll most likely get unknown as the answer, or the solver will loop indefinitely.