2

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!

Epic Gamer_1
  • 104
  • 3
  • 12

2 Answers2

3

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.

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
3

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
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • for any consideration, do you think that it should throws an error -nan for example-? or returning `false` would be enough? – Ahmad F Apr 09 '17 at 02:21
  • It is a Boolean true or false you can add a precondition but returning false I think it is enough – Leo Dabus Apr 09 '17 at 02:24