Red One Red One -4 years ago 205
Swift Question

Prime Numbers Swift 3

After hours of Googling, I'm still at a standstill. I would appreciate if someone would point out the error in my formula or coding choice. Please keep in mind I'm new to Swift. I'm not used to non C-style for loops.

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!"
}
}
}


I didn't know the formula on how to find a prime number. After looking up multiple formulas I have sorta settled on this one. Every result is a prime number, however. So my if condition is wrong. I just don't know how to fix it.

Answer Source

Check my algorithm.It works.But I'm not sure this is an effective algorithm for prime number

   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!")
}
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download