Epic Gamer_1
Epic Gamer_1

Reputation: 114

Swift 3 - Find if the Number is a perfect Square

I want to know if there is a way of finding if a number is a perfect square in Swift. I have the user enter a number to check if it is a perfect square. Is there a statement or a function? Thank you in advance!

Upvotes: 2

Views: 2507

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236568

edit/update: Swift 5.2

extension BinaryInteger {
    var isPerfectSquare: Bool {
        guard self >= .zero else { return false }
        var sum: Self = .zero
        var count: Self = .zero
        var squareRoot: Self = .zero
        while sum < self {
            count += 2
            sum += count
            squareRoot += 1
        }
        return squareRoot * squareRoot == self
    }
}

Playground

4.isPerfectSquare     // true
7.isPerfectSquare     // false
9.isPerfectSquare     // true
(-9).isPerfectSquare  // false

Upvotes: 4

Michael Dautermann
Michael Dautermann

Reputation: 89569

Try something like this:

var number = 9.0

let root = sqrt(number)
let isInteger = floor(root) == root
print("\(root) is \(isInteger ? "perfect" : "not perfect")")

That "isInteger" bit I found in this related question.

Upvotes: 3

Related Questions