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.
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.
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
This prime checking function and extension is the most efficient as it checks the divisibility of only integers.
Complexity:
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 }
}
}
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.
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.
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
A single-liner that:
func isPrime(_ n: Int) -> Bool {
return (2...Int(Double(n).squareRoot())).lazy.filter({ n % $0 == 0 }).first == nil
}
func FindPrime(number: Int) -> Bool {
guard number >= 2 else { return false }
for i in 2 ..< number {
if number % i == 0 {
return false
}
}
return true
}
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
}
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
}
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)
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)
In Swift 3:
func prime(_ number: Int) -> Bool {
return (1...number).filter({number % $0 == 0}).count <= 2
}
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 :
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 !
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)
}
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
}
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
}
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"
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))
//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))
Add just these 2-3 line of code:
for i in 2..<number {
if (number % i == 0) {
print("\(number) is not prime.")
}
}