for in 循环与 Swift 中的 where 子句

for in loop with where clause in Swift

我尝试将一些功能更新到 Swift 2.1。原来的工作代码是:

import func Darwin.sqrt
func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) }

func sigma(n: Int) -> Int {
    // adding up proper divisors from 1 to sqrt(n) by trial divison
    if n == 1 { return 0 } // definition of aliquot sum
    var result = 1
    let root = sqrt(n)
    for var div = 2; div <= root; ++div {
        if n % div == 0 {
            result += div + n/div
        }
    }
    if root*root == n { result -= root }
    return (result)
}
print(sigma(10))
print(sigma(3))

更新 for 循环后,我收到最后一行的运行时错误。知道为什么会这样吗?

import func Darwin.sqrt
func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) }

func sigma(n: Int) -> Int {
    // adding up proper divisors from 1 to sqrt(n) by trial divison
    if n == 1 { return 0 } // definition of aliquot sum
    var result = 1
    let root = sqrt(n)
    for div in 2...root where n % div == 0 {
            result += div + n/div
    }
    if root*root == n { result -= root }
    return (result)
}
print(sigma(10))
print(sigma(3)) //<- run time error with for in loop

当您将 3 传递给 sigma 时,您的范围 2...root 变得无效,因为左侧 root 小于右侧 2.

The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.

root被赋值为sqrt(n),也就是说为了让2...root范围保持有效,n必须在22以上.

您可以通过为右侧提供下限来修复,即

for div in 2...max(root,2) where n % div == 0 {
    ...
}

但是,此时您使用常规 for 循环的解决方案更具可读性。