How to resolve the algorithm Farey sequence step by step in the Prolog programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Farey sequence step by step in the Prolog programming language

Table of Contents

Problem Statement

The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series.

Each Farey sequence:

The Farey sequences of orders   1   to   5   are:

The length   (the number of fractions)   of a Farey sequence asymptotically approaches:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Farey sequence step by step in the Prolog programming language

Source code in the prolog programming language

task(1) :-
	between(1, 11, I),
	farey(I, F),
	write(I), write(': '),
	rwrite(F), nl, fail; true.

task(2) :- between(1, 10, I),
	I100 is I*100,
	farey( I100, F),
	length(F,N),
	write('|F('), write(I100), write(')| = '), writeln(N), fail; true.

% farey(+Order, Sequence)
farey(Order, Sequence) :-
  bagof( R,
	 I^J^(between(1, Order, J), between(0, J, I), R is I rdiv J),
	 S),
  predsort( rcompare, S, Sequence ).

rprint( rdiv(A,B) ) :- write(A), write(/), write(B), !.
rprint( I ) :- integer(I), write(I), write(/), write(1), !.

rwrite([]).
rwrite([R]) :- rprint(R).
rwrite([R, T|Rs]) :- rprint(R), write(', '), rwrite([T|Rs]).

rcompare(<, A, B) :- A < B, !.
rcompare(>, A, B) :- A > B, !.
rcompare(=, A, B) :- A =< B.


  

You may also check:How to resolve the algorithm Loops/For step by step in the Arturo programming language
You may also check:How to resolve the algorithm Verify distribution uniformity/Chi-squared test step by step in the zkl programming language
You may also check:How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Wren programming language
You may also check:How to resolve the algorithm Guess the number step by step in the Java programming language
You may also check:How to resolve the algorithm Levenshtein distance step by step in the Mathematica/Wolfram Language programming language