我打算找出直到N的质数。for循环外的代码没有增加。在这种情况下,答案打印为2。
let limit = Int(readLine()!)!
var factors = 2 // as prime no.s only have 2 factors
var countFactors = 0
var prime = [Int]() //array to store prime nos
for number in 2..<limit { // to count from 2 till N
for i in 1...number {
if(number%i == 0){
countFactors += 1
}
}
if(countFactors == factors){
prime.append(n)
}
}
for items in prime {
print(items)
}
答案 0 :(得分:0)
1)您的代码无法编译。你可能是说
prime.append(number)
2)发生意外行为的原因是,您忘记了在外循环的每次迭代中重置countFactors
...
for number in 2..<limit { // to count from 2 till N
countFactors = 0
for i in 1...number {
...