Posts

Showing posts with the label Prime

Adventures In Prolog - Euler7 and the Nth Prime

Building on our previous prime-related posts, today's post will cover a solution to Project Euler's 7th Problem, i.e. finding the 10001st prime. Now, the solution to this problem can be easily expressed in thought and then converted to some programming language … Starting with the lowest and first prime – 2 - , we check each subsequent number j > i, for primality. Whenever we find a j such that j is prime, we increment a prime counter c by one and continue testing numbers k > j. This is done until c reaches the number 10001. The Prolog code below is an expression of this idea, added with some prime numbers found during the process of finding the 10001st prime. This means, given the border of some prime interval, i.e. 100th prime = i and 200th prime = j, we may start looking for the 150th prime within the number interval [i,j], instead of starting at 2 and checking each number until the prime counter reaches 150. Also, we might have defined the euler_7 predicate to be dyna...

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