How to resolve the algorithm Stern-Brocot sequence step by step in the PL/I programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Stern-Brocot sequence step by step in the PL/I programming language
Table of Contents
Problem Statement
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
Show your output on this page.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Stern-Brocot sequence step by step in the PL/I programming language
Source code in the pl/i programming language
sternBrocot: procedure options(main);
%replace MAX by 1200;
declare S(1:MAX) fixed;
/* find the first occurrence of N in S */
findFirst: procedure(n) returns(fixed);
declare (n, i) fixed;
do i=1 to MAX;
if S(i)=n then return(i);
end;
end findFirst;
/* find the greatest common divisor of A and B */
gcd: procedure(a, b) returns(fixed) recursive;
declare (a, b) fixed;
if b = 0 then return(a);
return(gcd(b, mod(a, b)));
end gcd;
/* calculate S(i) up to MAX */
declare i fixed;
S(1) = 1; S(2) = 1;
do i=2 to MAX/2;
S(i*2-1) = S(i) + S(i-1);
S(i*2) = S(i);
end;
/* print first 15 elements */
put skip list('First 15 elements: ');
do i=1 to 15;
put edit(S(i)) (F(2));
end;
/* find first occurrences of 1..10 and 100 */
do i=1 to 10;
put skip list('First',i,'at',findFirst(i));
end;
put skip list('First ',100,'at',findFirst(100));
/* check GCDs of adjacent pairs up to 1000th element */
do i=2 to 1000;
if gcd(S(i-1),S(i)) ^= 1 then do;
put skip list('GCD of adjacent pair not 1 at i=',i);
stop;
end;
end;
put skip list('All GCDs of adjacent pairs are 1.');
end sternBrocot;
You may also check:How to resolve the algorithm Hello world/Newbie step by step in the Pixilang programming language
You may also check:How to resolve the algorithm Count occurrences of a substring step by step in the AArch64 Assembly programming language
You may also check:How to resolve the algorithm Intersecting number wheels step by step in the Nim programming language
You may also check:How to resolve the algorithm String length step by step in the Symsyn programming language
You may also check:How to resolve the algorithm Sum of elements below main diagonal of matrix step by step in the Java programming language