gpt4 book ai didi

swift - 素数 Swift 3

转载 作者:行者123 更新时间:2023-11-28 12:29:23 27 4
gpt4 key购买 nike

经过几个小时的谷歌搜索,我仍然处于停滞状态。如果有人指出我的公式或编码选择中的错误,我将不胜感激。请记住我是 Swift 的新手。我不习惯非 C 风格的 for 循环。

    if textField.text != "" {
input = Double(textField.text!)! // parse input

// return if number less than 2 entered
if input < 2 {
resultLabel.text = "Enter a number greater than or equal to 2."

return;
}

// get square root of input and parse to int
inputSquared = Int(sqrt(input));

// loop from 2 to input iterating by 1
for i in stride(from: 2, through: input, by: 1) {
if inputSquared % Int(i) == 0 {
resultLabel.text = "\(Int(input)) is not a prime number."
}
else {
resultLabel.text = "\(Int(input)) is a prime number!"
}
}
}

我不知道如何找到质数的公式。在查找了多个公式后,我已经确定了这个。然而,每个结果都是质数。所以我的if条件是错误的。我只是不知道如何修复它。

最佳答案

检查我的算法。它有效。但我不确定这是一个有效的素数算法

   var input:Int = 30
var isPrime:Bool = true


if(input == 2){
print("Input value 2 is prim number")
}
else if(input < 2){
print("Input value must greater than 2")
}
else{
for i in 2...input-1{
if((input%i) == 0){
isPrime = false
break;
}
}
if(isPrime){
print("Your Input Value \(input) is Prime!")
}
}

关于swift - 素数 Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42478949/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com