SquareRoot.swift 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //
  2. // SquareRoot.swift
  3. // CS.BigInt
  4. //
  5. // Created by Károly Lőrentey on 2016-01-03.
  6. // Copyright © 2016-2017 Károly Lőrentey.
  7. //
  8. //MARK: Square Root
  9. extension CS.BigUInt {
  10. /// Returns the integer square root of a big integer; i.e., the largest integer whose square isn't greater than `value`.
  11. ///
  12. /// - Returns: floor(sqrt(self))
  13. public func squareRoot() -> CS.BigUInt {
  14. // This implementation uses Newton's method.
  15. guard !self.isZero else { return CS.BigUInt() }
  16. var x = CS.BigUInt(1) << ((self.bitWidth + 1) / 2)
  17. var y: CS.BigUInt = 0
  18. while true {
  19. y.load(self)
  20. y /= x
  21. y += x
  22. y >>= 1
  23. if x == y || x == y - 1 { break }
  24. x = y
  25. }
  26. return x
  27. }
  28. }
  29. extension CS.BigInt {
  30. /// Returns the integer square root of a big integer; i.e., the largest integer whose square isn't greater than `value`.
  31. ///
  32. /// - Requires: self >= 0
  33. /// - Returns: floor(sqrt(self))
  34. public func squareRoot() -> CS.BigInt {
  35. precondition(self.sign == .plus)
  36. return CS.BigInt(sign: .plus, magnitude: self.magnitude.squareRoot())
  37. }
  38. }