'Prime numbers print from range 2...100

I have been assigned with a task to print prime numbers from a range 2...100. I've managed to get most of the prime numbers but can't figure out how to get rid of 9 and 15, basically multiples of 3 and 5. Please give me your suggestion on how can I fix this.

for n in 2...20 {
    if n % 2 == 0 && n < 3{
        print(n)
    } else if n % 2 == 1 {
        print(n)
    } else if n % 3 == 0 && n > 6  {
    }
}

This what it prints so far:

2
3
5
7
9
11
13
15
17
19


Solution 1:[1]

One of effective algorithms to find prime numbers is Sieve of Eratosthenes. It is based on idea that you have sorted array of all numbers in given range and you go from the beginning and you remove all numbers after current number divisible by this number which is prime number. You repeat this until you check last element in the array.

There is my algorithm which should do what I described above:

func primes(upTo rangeEndNumber: Int) -> [Int] {
    let firstPrime = 2
    guard rangeEndNumber >= firstPrime else {
        fatalError("End of range has to be greater than or equal to \(firstPrime)!")
    }
    var numbers = Array(firstPrime...rangeEndNumber)

    // Index of current prime in numbers array, at the beginning it is 0 so number is 2
    var currentPrimeIndex = 0

    // Check if there is any number left which could be prime
    while currentPrimeIndex < numbers.count {
        // Number at currentPrimeIndex is next prime
        let currentPrime = numbers[currentPrimeIndex]

        // Create array with numbers after current prime and remove all that are divisible by this prime
        var numbersAfterPrime = numbers.suffix(from: currentPrimeIndex + 1)
        numbersAfterPrime.removeAll(where: { $0 % currentPrime == 0 })

        // Set numbers as current numbers up to current prime + numbers after prime without numbers divisible by current prime
        numbers = numbers.prefix(currentPrimeIndex + 1) + Array(numbersAfterPrime)

        // Increase index for current prime
        currentPrimeIndex += 1
    }

    return numbers
}

print(primes(upTo: 100)) // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
print(primes(upTo: 2)) // [2]
print(primes(upTo: 1)) // Fatal error: End of range has to be greater than or equal to 2!

Solution 2:[2]

what is the Prime num : Prime numbers are the positive integers having only two factors, 1 and the integer itself,

 //Funtion Call 
findPrimeNumberlist(fromNumber: 1, toNumber: 100)

//You can print any range Prime number using this fucntion. 

func findPrimeNumberlist(fromNumber:Int, toNumber: Int)
{
 for i in fromNumber...toNumber
        {
            var isPrime = true
            if i <= 1 { // number must be positive integer
                isPrime = false 
            }
            else if i <= 3 {
                isPrime = true
            }
            else {
                for j in 2...i/2 // here i am using loop from 2 to i/2 because it will reduces the  iteration.
                {
                    if i%j == 0 { // number must have only 1 factor except 1. so use break: no need to check further 
                        isPrime = false
                        break
                    }
                }
            }
            if isPrime  {
                print(i)
            }
        }
}

Solution 3:[3]

func getPrimeNumbers(rangeOfNum: Int) -> [Int]{
var numArr = [Int]()
var primeNumArr = [Int]()
var currentNum = 0

for i in 0...rangeOfNum{
    currentNum = i

    var counter = 0

    if currentNum > 1{
        numArr.append(currentNum)

        for j in numArr{
            if currentNum % j == 0{
                counter += 1
            }
        }
        
        if counter == 1{
            primeNumArr.append(currentNum)
        }
        
    } 
}

print(primeNumArr)
print(primeNumArr.count)
return primeNumArr
}

Then just call the function with the max limit using this

getPrimeNumbers(rangeOfNum: 100)

What is happening in above code:

  1. The numArr is created to keep track of what numbers have been used

  2. Any number that is prime number is added/appended to primeNumArr

  3. Current number shows the number that is being used at the moment

  4. We start from 0 ... upto our range where we need prime numbers upto (with little modification it can be changed if the range starts from other number beside 0)

  5. Remember, for a number to be Prime it should have 2 divisor means should be only completely divisible by 2 numbers. First is 1 and second is itself. (Completely divisible means having remainder 0)

  6. The counter variable is used to keep count of how many numbers divide the current number being worked on.

  7. Since 1 is only has 1 Divisor itself hence its not a Prime number so we start from number > 1.

  8. First as soon as we get in, we add the current number being checked into the number array to keep track of numbers being used

  9. We run for loop to on number array and check if the Current Number (which in our case will always be New and Greater then previous ones) when divided by numbers in numArr leaves a remainder of 0. If Remainder is 0, we add 1 to the counter. Since we are already ignoring 1, the max number of counter for a prime number should be 1 which means only divisible by itself (only because we are ignoring it being divisible by 1) Hence if counter is equal to 1, it confirms that the number is prime and we add it to the primeNumArr

And that's it. This will give you all prime numbers within your range.

PS: This code is written on current version of swift

Solution 4:[4]

Optimised with less number of loops
Considered below conditions

  1. Even Number can not be prime number expect 2 so started top loop form 3 adding 2

  2. Any prime number can not multiplier of even number expect 2 so started inner loop form 3 adding 2

  3. Maximum multiplier of any number if half that number

    var primeNumbers:[Int] = [2]
    for index in stride(from: 3, to: 100, by: 2) {
        var count = 0
        for indexJ in stride(from: 3, to: index/2, by: 2) {
            if index % indexJ == 0 {
                count += 1
            }
            if count == 1 {
                break
            }
        }
        if count == 0 {
            primeNumbers.append(index)
        }
    }
    print("primeNumbers ===", primeNumbers)
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Fahad Saleem
Solution 4