How to resolve the algorithm Stern-Brocot sequence step by step in the Scala programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Stern-Brocot sequence step by step in the Scala 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 Scala programming language

Source code in the scala programming language

lazy val sbSeq: Stream[BigInt] = {
  BigInt("1") #:: 
  BigInt("1") #:: 
  (sbSeq zip sbSeq.tail zip sbSeq.tail).
  flatMap{ case ((a,b),c) => List(a+b,c) }
}
  
// Show the results
{
println( s"First 15 members: ${(for( n <- 0 until 15 ) yield sbSeq(n)) mkString( "," )}" )
println
for( n <- 1 to 10; pos = sbSeq.indexOf(n) + 1 ) println( s"Position of first $n is at $pos" )
println
println( s"Position of first 100 is at ${sbSeq.indexOf(100) + 1}" )
println
println( s"Greatest Common Divisor for first 1000 members is 1: " +
  (sbSeq zip sbSeq.tail).take(1000).forall{ case (a,b) => a.gcd(b) == 1 } )
}


  

You may also check:How to resolve the algorithm Poker hand analyser step by step in the Ruby programming language
You may also check:How to resolve the algorithm Factorial step by step in the REBOL programming language
You may also check:How to resolve the algorithm Empty string step by step in the K programming language
You may also check:How to resolve the algorithm The Twelve Days of Christmas step by step in the C programming language
You may also check:How to resolve the algorithm Conditional structures step by step in the OxygenBasic programming language