Validating primes
Let's see how to use logic programming to check for prime numbers. We will use the constructs available in logpy to determine which numbers in the given list are prime, as well as finding out if a given number is a prime or not.
Create a new Python file and import the following packages:
import itertools as it import logpy.core as lc from sympy.ntheory.generate import prime, isprime
Next, define a function that checks if the given number is prime depending on the type of data. If it's a number, then it's pretty straightforward. If it's a variable, then we have to run the sequential operation. To give a bit of background, the method conde is a goal constructor that provides logical AND and OR operations. The method condeseq is like conde, but it supports generic iterator of goals:
# Check if the elements of x are prime
def check_prime(x):
if lc.isvar(x):
return lc.condeseq([(lc.eq, x, p)] for p in map(prime, it.count(1)))
else:
return lc.success...