Posts

Showing posts from July, 2009

Adventures in Prolog - Some more Primes

Again, we are going to tackle some problems mentioned in the list of 99-Prolog problems. Today's post builds upon the gcd predicate defined last time to attack problems: P31 = is_prime P35 = prime_factors P36 = prime_factors_mult P39 = prime_list Now, building on the previously defined gcd predicate, on may define a prime inductively: a prime is a number which is only (divisible by one and itself) the smallest prime is 2 any number greater than 2 is either composite or prime Building on this definition we may translate the smallest prime into a Prolog predicate quite easily. To determine the primeness/composibility of any number greater than 2, one may use the gcd predicate. Recalling that a prime p is a number which cannot be divided by any number in ]1, p[, the following predicate may be given: is_prime(2) :- !. is_prime(3) :- !. is_prime(X) :- X >= 2, UpperBound is round(sqrt(X)) + 1, is_prime_t(X, 2, UpperBound), !. is_prime_t(_, UpperBound, UpperBound). is_prime_t(X, ...

Adventures in Prolog - GCD and Coprime

Today's post follows the tradition of the my last post, i.e. it continues with another problem stated in the list of 99 Prolog problems. Today, we are going to have a look at problem 32 and 33. Problem 32 concerns the implementation of a greatest common divisor predicate (gcd). In an earlier post, I implemented a gcd routine in Python . We are going to reuse this definition of gcd here, using a ternary predicate/relation. The Prolog definition of gcd makes use of gcd's recursive definition, which are: the gcd of two numbers x and y is equal to the gcd of x - y and y for y the gcd of some number and 0 is the number the gcd of some number and 1 is 1 Now, given the above properties (and some more) a possible gcd predicate might look like this: gcd(A, 0, A) :- !. %includes gcd(0,0) gcd(1, _, 1) :- !. gcd(A, A, A) :- !. gcd(A, B, GCD) :- A X is B - A, gcd(X, A, GCD). gcd(A, B, GCD) :- X is A - B, gcd(X, B, GCD). Provided the above definition of gcd, the solution to proble...

Adventures In Prolog - Duplicate List Members

Today's post is about problem 14 from the list of 99 Prolog problems (see here ): (*) Duplicate the elements of a list. Example: ?- dupli([a,b,c,c,d],X). X = [a,a,b,b,c,c,c,c,d,d] Since the problem is marked with one star, a solution should be within reach. Now, to duplicate each element of the list, we do the following: We traverse the list element by element until we reach the last element, i.e. the empty list. For each element (excluding the empty list), the element is added twice to a newly built output list. Given the above solution statement, a possible translation to Prolog code might look like this: dupli([], []). dupli(L, O) :- dupli_t(L, [], O). dupli_t([], Current, Current). dupli_t([H|T], CList, OutList) :- append(CList, [H, H], IntermediateList), dupli_t(T, IntermediateList, OutList).