我是 swift 的初学者。我只是想编写一个程序来打印第 n 个素数,但在将 sqrt 函数转换为 int 时遇到一些问题。下面是与 c/c++ 配合良好的代码。
func nthPrime(n: Int64)
{
var i:Int64=4,j:Int64=0, prime:Int64=0
var count:Int64=0
while count != n
{
for (j=2 ; j < Int64((sqrt(i))) + 1 ; j++) //Shows error cant invoke init with argument list of type (@lvalue Int64,$T9)
{
if(i%j == 0)
{
i++
break
}
else if(j == Int64(sqrt(i)))
{
count++
i++
}
}
}
println("\(n)th prime is \(prime)")
}
是否可以在 swift 中进行这种比较?我知道如果我将 var i 和 j 更改为 Double ,它将消除错误,但代码将无法正常工作。还有其他建议吗
最佳答案
sqrt方法输入参数需要是Double。所以你需要将其转换为 Double。您还需要使用称为 ceil 的数学方法。
In mathematics and computer science, the floor and ceiling functions map a real number to the largest previous or the smallest following integer, respectively.
它将产生 Double,因此您需要将结果再次转换回 Integer。尝试像这样使用它:
Int(ceil(sqrt(Double(i))))
//
extension Int {
var isPrime:Bool{
if self < 2 { return false }
let squareRoot = Int(sqrt(Double(self)))
if squareRoot * squareRoot == self { return false }
for i in 2..<Int(ceil(sqrt(Double(self)))) {
if self % i == 0 { return false }
}
return true
}
}
//
1.isPrime // false
2.isPrime // true
3.isPrime // true
4.isPrime // false
5.isPrime // true
6.isPrime // false
7.isPrime // true
8.isPrime // false
9.isPrime // false
10.isPrime // false
11.isPrime // true
//
let myInt = 7
if myInt.isPrime {
// do this
} else {
// do that
}
//
var twoDigitsPrimeNumbers:[Int] = []
for number in 1..<100 {
if number.isPrime {
twoDigitsPrimeNumbers.append(number)
}
}
println(twoDigitsPrimeNumbers.description) // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
func nthPrime(nth:Int)-> Int {
var primeCounter = 0
var number = 2
while true {
if number.isPrime {
primeCounter++
if nth == primeCounter { return number}
}
number++
}
}
nthPrime(1000) // 7,919
关于ios - 快速将 double 转换为 Int64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28757771/