Best way to calculate the square root of any number in ios , Objective C and Swift
The sqrt
function (and other mathematical functions as well) is
available in the standard libraries on all OS X and iOS platforms.
It can be used from (Objective-)C:
#include "math.h"
double sqrtFive = sqrt(5.0);
and from Swift:
import Darwin // or Foundation, Cocoa, UIKit, ...
let sqrtFive = sqrt(5.0)
Swift 5 calling squareRoot()
squareRoot()
is a method defined in the FloatingPoint protocol, to which Double
and Float
conform, but not integer types like Int
.
Therefore you have to convert the Int
to Double
(and the result back to Int
):
let upperBound = Int(Double(number).squareRoot())
for i in 2..<upperBound {
The other example
let test = 100.squareRoot()
compiles because both Int
and Double
conform to the ExpressibleByIntegerLiteral
protocol, i.e. can be initialized from an integer literal. Here the compiler automatically infers 100
to be a floating point value because that is the only way to make the code compile. It becomes obvious here:
let test = 123.squareRoot()
print(test) // 11.090536506409418
Generic square root in Swift
I see that you're using using a custom Arithmetic
protocol to constraint the generic.
My approach would be to declare 2 required methods in that protocol: toDouble()
and fromDouble()
, and implement both in Float
, Double
and Int
extensions. Note that fromDouble()
should be a static method.
This way you can convert T
to Double
, hence be able to use sqrt()
, and convert back from Double
to T
.
Last, there's a bug in your code: if left
is an empty vector, the function will crash, because the code in the loop will never be executed, so result
will keep its nil
initial value. The forced unwrapping in the return
statement will fail, causing the exception.
Rooting without using sqrt in Swift
OK, so here's your code after I aligned it.
import Foundation
func rooting(number: Int) -> Int {
for i in 1...100 {
if i * i == number {
var Root = i
break
}
return Root
}
return Root
}
print(rooting(number: 9))
The problem is that you are creating the Root
variable in a scope that ends before you try to use the variable. Essentially, the Root
variable only exists in the following segment:
import Foundation
func rooting(number: Int) -> Int {
for i in 1...100 {
if i * i == number {
var Root = I //Root variable starts existing
break
} //Root variable no longer exists
return Root
}
return Root
}
print(rooting(number: 9))
This is because it is scoped to the if
statement. To solve this specific problem, you could change your code to this:
import Foundation
func rooting(number: Int) -> Int {
for i in 1...100 {
if i * i == number {
return i
}
}
}
print(rooting(number: 9))
since you don't do anything with Root
other than return it. Of course, this still won't work, as you aren't guaranteed to return anything (what if number
is 8?), and you said that the function will always return an Int
.
Here's a quick example of an implementation of a rooting function:
import Foundation
func rooting(number: Int) -> Int? {
guard number > 0 else { return nil }
for i in 0...(number/2) {
if i * i == number {
return i
}
}
return nil
}
print(rooting(number: 9))
If the number has a square root, it will be returned; otherwise, the function returns nil
.
How to calculate the 6th root of 2 in Swift?
To compute the 6th root of 2:
pow(2.0, 1.0/6.0)
You just need to use Double
s.
There are multiple versions of pow
for different data types. By using the floating point literals, Swift will infer them be of type Double
and select pow
with this signature:
func pow(_: Double, _: Double) -> Double
Or you can use logarithms (nth root of x is exp(log(x)/n)
where x
and n
are Double
s:
exp(log(2.0) / 6.0)
how to get the nearest Int floored from a sqrt of an Int?
If you want to call generatePrimes with a Double
generatePrimes(to: floor(sqrt(Double(n)))
or if you want to call it with an Int
generatePrimes(to: Int(floor(sqrt(Double(n))))
Related Topics
Swift How to Cast from Int? to String
Scene Kit Performance with Cube Test
Function Taking a Variable Number of Arguments
Nested Types Inside a Protocol
Codable and Xmlparser in Swift
Using Foreach with a an Array of Bindings (Swiftui)
Avoid Consecutive "If Let" Declarations in Swift
How to Open Url in Safari and the Get Back to the App Under Uitests in Xcode 7
How in Swift to Convert Int16 to Two Uint8 Bytes
Detect Ethernet/Wifi Network Change
Get Rawvalue from Enum in a Generic Function
Swiftui - Using Geometryreader Without Modifying the View Size
How to Automatically Reflect Coredata+Icloud Changes in Swiftui View
Iterate an Array W/ Explicit Object Type in Swift