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

1 Answer

0 votes
package main

import (
    "fmt"
    "sort"
)

func containsPythagoreanTripletNumbers(arr []int) bool {
    squares := make([]int, len(arr))
    for i, val := range arr {
        squares[i] = val * val
    }

    sort.Ints(squares)

    for i := len(squares) - 1; i >= 2; i-- {
        a := 0
        b := i - 1
        for a < b {
            if squares[a]+squares[b] == squares[i] {
                return true
            } else if squares[a]+squares[b] < squares[i] {
                a++
            } else {
                b--
            }
        }
    }
    return false
}

func main() {
    input := []int{4, 7, 3, 1, 5} // 3*3 + 4*4 = 5*5 // 9 + 16 = 25
    
    if containsPythagoreanTripletNumbers(input) {
        fmt.Println("The array contains a Pythagorean triplet.")
    } else {
        fmt.Println("The array does not contain a Pythagorean triplet.")
    }
}



/*
run:

The array contains a Pythagorean triplet.

*/

 



answered Jul 25, 2025 by avibootz
...