How to resolve the algorithm Brilliant numbers step by step in the Scala programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Brilliant numbers step by step in the Scala programming language

Table of Contents

Problem Statement

Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10. Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Brilliant numbers step by step in the Scala programming language

Source code in the scala programming language

val primes = 2 #:: LazyList.from(3, 2)    // simple prime
    .filter(p => (3 to math.sqrt(p).ceil.toInt by 2).forall(p % _ > 0))

def brilliantSemiPrimes(limit: Int): Seq[Int] = {
  def iter(primeList: LazyList[Int], bLimit: Int, acc: Seq[Int]): Seq[Int] = {
    val (start, tail) = (primeList.head, primeList.tail)
    val brilliants = primeList
            .takeWhile(_ <= bLimit)
            .map(_ * start)
            .takeWhile(_ <= limit)
    if (brilliants.isEmpty) return acc
    val bLimit1 = if (tail.head > bLimit) 10 * bLimit else bLimit
    iter(tail, bLimit1, brilliants.toSeq ++ acc)
  }
  iter(primes, 10, Seq()).sorted
}

@main def main = {
  val start = System.currentTimeMillis
  val brList = brilliantSemiPrimes(1500).take(100)
  val duration = System.currentTimeMillis - start
  for (group <- brList.grouped(20))
      println(group.map("%4d".format(_)).mkString(" "))
  println(s"time elapsed: $duration ms\n")

  for (limit <- (1 to 6).map(math.pow(10,_).toInt)) {
    val start = System.currentTimeMillis
    val (bril, index) = brilliantSemiPrimes((limit * 1.25).toInt)
            .zipWithIndex
            .dropWhile((b, _i) => b < limit)
            .head
    val duration = System.currentTimeMillis - start
    println(f"first >= $limit%7d is $bril%7d at position ${index+1}%5d [time(ms) $duration%2d]")
  }
}


  

You may also check:How to resolve the algorithm Mian-Chowla sequence step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Sorting algorithms/Merge sort step by step in the MATLAB programming language
You may also check:How to resolve the algorithm Reverse a string step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm XML/DOM serialization step by step in the ARM Assembly programming language
You may also check:How to resolve the algorithm Julia set step by step in the Maxima programming language