我的逻辑怎么了?9怎么能同时以素数而不是素数的形式出现呢?
这对0,1,2,3,4,5,6,7,8都起作用,但在9。。。

var userInput = 9

if userInput == 0 {
    print("0 is not a prime number")
} else if userInput == 1 {
    print("1 is not a prime number")
} else if userInput == 2 {
    print("2 is a prime number")
} else {
    for var i = 2; i < userInput; i = i + 1 {
        if userInput % i == 0 {
            print("\(userInput) is not a prime number")
            break
        } else {
            print("\(userInput) is a prime number")
            break
        }
    }
}

最佳答案

这种逻辑有缺陷:

for var i = 2; i < userInput; i = i + 1 {
    if userInput % i == 0 {
        print("\(userInput) is not a prime number")
        break
    } else {
        print("\(userInput) is a prime number")
        break
    }
}

if-else是错误的。相反,您需要首先循环遍历for循环的整个if部分,反复测试每个数字是否是一个因子(if userInput % i == 0);然后,只有在完成循环并且仍然没有发现因子的情况下,才能声明这必须是一个素数。
然而,如果你像以前那样把所有事情都放在一个平的顶层,你会发现很难成功地写出这种逻辑。问题是当你处于顶层时,你没有办法真正退出。因此,你的逻辑要求你把每件事都放在一个函数中,从中你可以通过说“cc>”来强制提前退出。
在这次重写中,我已经做到了,而且我使用了一个比您的return更清晰(更快)的switch
func testForPrime(userInput:Int) {
    switch userInput {
    case 0: print("0 is not a prime number")
    case 1: print("1 is not a prime number")
    case 2: print("2 is a prime number")
    default:
        for i in 2..<userInput {
            if userInput % i == 0 {
                print("\(userInput) is not a prime number")
                return
            }
        }
        print("\(userInput) is a prime number")
    }
}

下面是测试方法:
for i in 0...20 {testForPrime(i)}

输出:
0 is not a prime number
1 is not a prime number
2 is a prime number
3 is a prime number
4 is not a prime number
5 is a prime number
6 is not a prime number
7 is a prime number
8 is not a prime number
9 is not a prime number
10 is not a prime number
11 is a prime number
12 is not a prime number
13 is a prime number
14 is not a prime number
15 is not a prime number
16 is not a prime number
17 is a prime number
18 is not a prime number
19 is a prime number
20 is not a prime number

(请注意,我使用了Swift样式的for loop,而不是您的C样式的for loop。您应该习惯Swift样式,因为C-style for循环很快就会从语言中删除。)

关于swift - 素数确定程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34618046/

10-16 23:31