roberto tomás
roberto tomás

Reputation: 4687

how to get the nearest Int floored from a sqrt of an Int?

I need the largest int at or below the sqrt of n.

I am getting Cannot use mutating member on immutable value: 'sqrt' returns immutable value

func isPrime (n:Int) ->  Bool {
    if n < 2 { return false }

    generatePrimes(to: sqrt(Double(n)).round(.towardZero))

The same problem with .squareRoot

How can I generate to:Int here?

Upvotes: 2

Views: 480

Answers (2)

Martin R
Martin R

Reputation: 539925

There are two different methods in the FloatingPoint protocol:

mutating func round(_ rule: FloatingPointRoundingRule)
func rounded(_ rule: FloatingPointRoundingRule) -> Self

The first one mutates the receiver, and the second one returns a new value. You want to use the second one:

sqrt(Double(n)).rounded(.towardZero)

or

Double(n).squareRoot().rounded(.towardZero)

But if you need the result as an integer then it is simply

Int(Double(n).squareRoot())

because the conversion from Double to Int already truncates the result towards zero.

Upvotes: 6

Joakim Danielson
Joakim Danielson

Reputation: 51983

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))))

Upvotes: 0

Related Questions