for循环使用Swift中的where子句

时间:2016-01-08 11:05:02

标签: swift for-in-loop

我试图将一个小函数更新为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

1 个答案:

答案 0 :(得分:6)

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

  

关闭范围运算符2定义从(a...b)a的范围,并包含值bab的值不得大于a

b已分配root,这意味着为了使sqrt(n)范围保持有效,2...root必须高于2 2

您可以通过提供右侧的下限来确定,即

n

但是,此时使用常规for div in 2...max(root,2) where n % div == 0 { ... } 循环的解决方案更具可读性。