0

I'm trying to make an app that checks whether a number is prime or not.

Can someone help me to check the number?

I need a simple answer, not incredibly advanced algorithms. I'm new to programming.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • 3
    possible duplicate of [Which is the fastest algorithm to find prime numbers?](http://stackoverflow.com/questions/453793/which-is-the-fastest-algorithm-to-find-prime-numbers) – Jan Jun 28 '15 at 23:05
  • 5
    I'm voting to close this question as off-topic because it's about math and shows no research whatsoever – David Brossard Aug 19 '18 at 00:51

18 Answers18

32

Here is a functional solution in Swift 3:

func isPrime(_ number: Int) -> Bool {
    return number > 1 && !(2..<number).contains { number % $0 == 0 }
}

It first makes sure the number is greater than one and then creates a range from 2 until the number (not including the number) and checks the number is not divisible by each number in the range

Wayne Ellery
  • 7,888
  • 1
  • 28
  • 45
  • 11
    functional lipstick over the slowest algorithm – Sten Petrov Aug 14 '18 at 18:32
  • 3
    This is very slow for large numbers. Assuming N is divisible by i takes 1 ms. Thus suppose, N = 1500450271 ( Prime ) Time taken = 1 ms * number of divisions ->1 ms * 1500450271 ->11.5 days.!! Alternatively, 1ms * number of divisions = 1ms * square root of 1500450271= approximately 40000ms = 40 seconds. – Alejandro Vargas May 07 '19 at 01:17
  • My mistake! Sorry not sure what happened. – ScottyBlades Jul 12 '22 at 05:35
14

Fastest Prime Checker

Swift 4.2, Xcode 10.1

This prime checking function and extension is the most efficient as it checks the divisibility of only formula integers.

Complexity: formula


Solution:

func isPrime(_ n: Int) -> Bool {
    guard n >= 2     else { return false }
    guard n != 2     else { return true  }
    guard n % 2 != 0 else { return false }
    return !stride(from: 3, through: Int(sqrt(Double(n))), by: 2).contains { n % $0 == 0 }
}

Extension:

extension Int {
    var isPrime: Bool {
        guard self >= 2     else { return false }
        guard self != 2     else { return true  }
        guard self % 2 != 0 else { return false }
        return !stride(from: 3, through: Int(sqrt(Double(self))), by: 2).contains { self % $0 == 0 }
    }
}

How it Works

This code's benefit over the other answers is that it doesn't check redundant numbers. This code only checks half the numbers up to the square root of the desired number.


Community
  • 1
  • 1
Noah Wilder
  • 1,656
  • 20
  • 38
  • Yes it is quite different @MartinR, it does not check multiples of 2 whereas [@shokuroff's answer](http://stackoverflow.com/a/44413339/1187415) does. I benchmarked both and found my answer to be 5-6x faster than the other answer. – Noah Wilder Dec 26 '18 at 18:58
  • 1
    That referred to your version from April. I have deleted my comment it because your code changed. – Martin R Dec 26 '18 at 21:26
6

I cannot reply because of reputation I have, but I find Wayne Ellery's method is brilliant. However just a little fix if it's possible..

// that's Swift 3.1
import Foundation

func isPrime(_ number: Int) -> Bool {
    // right below
    if number == 2 || number == 3 { return true }
    let maxDivider = Int(sqrt(Double(number)))
    return number > 1 && !(2...maxDivider).contains { number % $0 == 0 }
}

All dividers of integer number with value more than sqrt(number) aren't necessary.

cmilr
  • 379
  • 4
  • 13
devshok
  • 737
  • 1
  • 8
  • 19
  • This is wrong in the case of number == 2, because maxDivider in this case is square root of 2 which is less than 2 and cannot form the upper bond. – Jun D Nov 11 '18 at 18:03
4

A simple method is to check all factors up to the square-root of the number. This is NOT the most efficient method, but is sufficient for most numbers you will likely be inputting in an iPhone app. (see https://en.wikipedia.org/wiki/Primality_test for more complex algorithms).

function is_prime(n: int)
    if n <= 1
        return false

    if n <= 3
        return true

    i = 2
    while i*i <= n
        if n % i == 0
           return false
        i = i + 1
    return true
slessans
  • 677
  • 4
  • 16
  • I have rolled back from the update by @Steven Kryskalla that suggested incrementing by two -- this is simply wrong: `i` is not the number being checked but the divisor. the divisor could be even or odd and thus it must be incremented by one. If you try the updated algorithm, for instance, it would tell you 45 is prime. – slessans Aug 19 '18 at 00:50
  • Good catch. I think what the original editor was trying to do was only test divisibility by 2 once, that way you could start i at 3 and increment by 2 each time, but the code wasn't correct. – Steven Kryskalla Aug 19 '18 at 05:59
3

A single-liner that:

  1. discards not primes faster (thanks to lazy evaluation).
  2. reduces the range in which to search for divisors.
func isPrime(_ n: Int) -> Bool {
  return (2...Int(Double(n).squareRoot())).lazy.filter({ n % $0 == 0 }).first == nil
}
kanobius
  • 756
  • 9
  • 12
3
func FindPrime(number: Int) -> Bool {
    guard number >= 2 else { return false }

    for i in 2 ..< number {
        if number % i == 0 {
            return false
        }
    }

    return true
}
  1. The problem with this function is that it’s computationally expensive: 16,777,259 is a prime number, so this solution will divide from 2 up to 16,777,258 and find that none of them work before deciding that the number is prime.

2.Consider this: if the number n is not prime, it means it can be reached by multiplying two factors, x and y. If both of those numbers were greater than the square root of n, then x * y would be greater than n, which is not possible. So, we can be sure that at least one of x or y is less than or equal to the square root of n.

func FindPrime(number: Int) -> Bool {
    guard number >= 2 else { return false }
    guard number != 2 else { return true }
    let max = Int(ceil(sqrt(Double(number))))

    for i in 2 ... max {
        if number % i == 0 {
            return false
        }
    }

    return true
}
2

Swift 2 example:

func is_prime(n: Int) -> Bool {
    if n <= 1 {
        return false
    }
    if n <= 3 {
        return true
    }
    var i = 2
    while i*i <= n {
        if n % i == 0 {
            return false
        }
        i = i + 1
    }
    return true
}
Aaron Lelevier
  • 19,850
  • 11
  • 76
  • 111
2
func divides(a: Int, b: Int) -> Bool {
    return a % b == 0
}

func countDivisors(number: Int) -> Int {
    var cnt = 0
    for i in 1...number {
        if divides(a: number, b: i) {
            cnt+=1
        }
    }
    return cnt
}



func isPrime(number: Int) -> Bool {
    return countDivisors(number: number) == 2
}

isPrime(number: 7)
tina
  • 37
  • 1
2
func checkPrimeOrNot(numberToCheck:Int)-> Bool{
    var isPrime : Bool = false
    if numberToCheck > 2  {
        for  n in 2...(numberToCheck - 1) {
            isPrime = (numberToCheck % n ) == 0  ? false : true
            if !isPrime{
                break
            }
        }
    } else {
        isPrime = numberToCheck == 1 ? true : false
        isPrime = numberToCheck == 0 ? false : true
    }
    return isPrime
}

You Can Call this function like this

let primeNumber = checkPrimeOrNot(numberToCheck: 23)

vinay
  • 132
  • 8
0

In Swift 3:

func prime(_ number: Int) -> Bool {
    return (1...number).filter({number % $0 == 0}).count <= 2
}
zyc
  • 344
  • 3
  • 7
  • 4
    +1 for single-line elegance. Just noting, as said elsewhere, only numbers up until the *square root* of your target number need to be checked for factors. Think about it: if, say, 16 or 17 isn't prime, you'll know by the time you check if it divides evenly by 5. For any composite number, the factors 'flip' around the sqrt. Take 16: (1, 16), (2, 8), (4, 4), (8, 2), (16, 1). Checking 8 is redundant since you must have also checked 2 on the way to get there. Replace all numbers with 'm' and 'n' and you have a proof! (Er, which I leave as an exercise :D ) – AmitaiB Mar 06 '18 at 14:42
0

I've just finished this program in order to learn syntax Swift4. Here's what I ended with :

import Foundation
import Darwin

var Timestamp: Double {
    return (NSDate().timeIntervalSince1970)
}

func checkPrime(number: Int) -> String {
    let num: Double = Double(number)
    let squareRoot: Double = Double(sqrt(num))
    let sqr: Int = Int(floor(squareRoot))
    var i: Int = 3
    while i <= sqr {
        if number % i == 0 {

            return "Too bad... \(number) is not a prime number, you can divide it by \(i) :/"
        }
        i += 2
    }

    return "You chose \(number) wisely. Definitely a prime number"
}

func isPrime(check: Int) -> String {
    switch check {
        case check where check <= 1 :
            return "Neither 1 nor numbers below are prime numbers."
        case 2 :
            return "Congratulations ! \(check) is the only even prime number !"
        case let check where check % 2 == 0 :
            return "There is only one even prime number, and it's definitely not \(check)..."
        default :
            return checkPrime(number: check)
    }
}

print("Please write Int to check if it's prime")
if let typed: String = readLine() {
    if let num: Int = Int(typed) {
        let start = Timestamp
        print(isPrime(check: num))
        print("calculated in \((Timestamp - start)*1000) milliseconds")
    } else {
        print("Please choose an integer between 0 and \(Int.max)")
    }
}

What's going on here is pretty simple, but it helped me understand a few things which I'd like to share with newbies like me !

First I found a Timestamp function here to calculate how much time my program take to check if a number is prime. That has nothing to do with prime number so let's not talk about it.

My first big problem was to get the input of the user. After looking for an equivalent of prompt in Swift, I realize that I always got a String as answer.
I found this convenient way that helped me a lot with understanding types in Swift and how to get from String to Int.

So here's the core of finding prime numbers :

First, the function isPrime evaluates the obvious.
I know it's not a prime if it's inferior or equal to 1. I learned that very weird syntax which I really need to get documented about

switch check {
    case check where check <= 1
}

I know 2 is the only even prime number
I know all others even numbers are not primes (with weird syntax)

If I pass this test, then I can really check if the number is prime :

I've learned that you don't have to evaluate all the numbers from 3 (remember, we excluded 2 and bellow) to the potentially prime number for two reasons :

  • If it's a multiple of any multiple of 2, it already has been excluded
  • If cannot multiply it with any integers from 3 to its square root, then it is prime. (more infos here)

So from here I had to get the square root of my number, for which I needed to switch my number from Int to Double. I needed to stock my result into an Int var so I can compare it to my incrementing number i (from 3 to sqrt).

After that I just had to check if my number % i wasn't equal to 0, in which case it's not a prime number. And as I've already eliminated even numbers, I can increment i by 2 each loop so I only check odd numbers.

It's my first contribution here so I really wish it will help. I'm pretty sure my code is far from perfect so don't hesitate to correct/improve it !

Ted
  • 22,696
  • 11
  • 95
  • 109
Zyigh
  • 425
  • 4
  • 16
0
func primeOrNot(input : Int){
    
    var flag : Bool = false;
    if (input > 2){
        for i in 2...input/2{
            if(input % i == 0){
                flag = true
                break;
            }
        }
    }else{
        flag = true
    }
    let result = (flag == false) ? "\(input) is prime!" : "\(input) is not prime!"
    debugPrint(result)
}
Manee ios
  • 1,112
  • 11
  • 14
0
func isPrime(n : Int) -> Bool {
 if n < 2 {
   return false
 }
 var i:Int = 2
 while i < n {
   if n % i == 0 {
     return false
    }
    i += 1
 }
    return true
}
My Tran Bui
  • 503
  • 1
  • 4
  • 7
-2

The following is a simple brute-force function to determine if a number is prime. It divides the target number by all positive integers less than itself (except for 1). If the remainder of any of the divisions is zero then obviously the target number is not prime. If no such divisors are found the number is then prime.

func isNumberPrime(_ number : Int) -> Bool{
    for n in 2..<number {
        if( number % n == 0){
            return false
        }
    }
    return true
}
-2
func isPrime(n : Int) -> Bool{
    var t = true
    if n <= 1 {
        print("Choose a number higher than one")
    } else {
        for y in 2...n {
            if y == n {
                t = true
                break
            } else if n % y == 0 {
                t = false
                break
            } else if n % y != 0 {
            }
        }
    }
    return t
}

print(isPrime(n: 51))
// This only answers for the number inputted, in this case "51"
jfelder
  • 17
  • 1
-2

Prime numbers are of the form 6f ± 1, excluding 2 and 3 where f is any integer

func isPrime(_ number: Int) -> Bool 
{

     if (number <= 1)
     {
        return false;
     }   

     // The check for the number 2 and 3
     if (number <= 3)
     {
        return true;
     }

     if (number%2 == 0 || number%3 == 0)
     {
        return false;
     }

     for var i in stride(from: 5, to: number/2, by: 6)
     {

        if (number%i == 0 || number%(i+2) == 0)
        {
           return false;
        }   
     }

     return true;
}

Time Complexity of the solution: O(sqrt(n))

H S W
  • 6,310
  • 4
  • 25
  • 36
-2
//not the best, but it works
let checkPrimeNumber = { (number: Int)-> [Int] in
var arr = Array<Int>()
for i in 2...number {
    if i==2 || i==3 || i==5 || i==7 {
        arr.append(i)
    }
    if (i%2 != 0) && (i%3 != 0) && (i%5 != 0) && (i%7 != 0) {
        arr.append(i)
    }
}
return arr

}

print(checkPrimeNumber(10))

-6

Add just these 2-3 line of code:

for i in 2..<number {
    if (number % i == 0) {
        print("\(number) is not prime.")
    }
}
Noah Wilder
  • 1,656
  • 20
  • 38
pooja
  • 23
  • 4