Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,844 questions

51,765 answers

573 users

How to check if an array contains the Pythagorean triplet numbers (a*a+b*b=c*c) in Scala

1 Answer

0 votes
object PythagoreanTripletChecker {

  def containsPythagoreanTriplet(arr: Array[Int]): Boolean = {
    val squares = arr.map(x => x * x).sorted

    for (i <- squares.length - 1 to 2 by -1) {
      var a = 0
      var b = i - 1

      while (a < b) {
        val sum = squares(a) + squares(b)
        if (sum == squares(i)) return true
        else if (sum < squares(i)) a += 1
        else b -= 1
      }
    }

    false
  }

  def main(args: Array[String]): Unit = {
    val input = Array(4, 7, 3, 1, 5) // 3*3 + 4*4 = 5*5 // 9 + 16 = 25
    
    if (containsPythagoreanTriplet(input))
      println("The array contains a Pythagorean triplet.")
    else
      println("The array does not contain a Pythagorean triplet.")
  }
}




/*
run:
 
The array contains a Pythagorean triplet.
 
*/

 



answered Jul 25, 2025 by avibootz
...