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

1 Answer

0 votes
import Foundation

func containsPythagoreanTriplet(_ arr: [Int]) -> Bool {
    let squares = arr.map { $0 * $0 }.sorted()

    for i in stride(from: squares.count - 1, through: 2, by: -1) {
        var a = 0
        var b = i - 1

        while a < b {
            let sum = squares[a] + squares[b]
            if sum == squares[i] {
                return true
            } else if sum < squares[i] {
                a += 1
            } else {
                b -= 1
            }
        }
    }

    return false
}

let input = [4, 7, 3, 1, 5] // 3*3 + 4*4 = 5*5 // 9 + 16 = 25

if containsPythagoreanTriplet(input) {
    print("The array contains a Pythagorean triplet.")
} else {
    print("The array does not contain a Pythagorean triplet.")
}



/*
run:

The array contains a Pythagorean triplet.

*/

 



answered Jul 25, 2025 by avibootz
...