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, ...