Reputation: 114
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
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
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