Print the first N
prime numbers.
Example
Input:
let N = 7
Expected value:
2
3
5
7
11
13
17
[collapse]
Hint1
A number is prime if it has exactly 2 distinct divisors (1 and itself). You could simply check all potential divisors for each number and count the numbers with exactly 2 divisors.
[collapse]
Hint2
Or you can learn about Eratosthene’s Sieve, which finds the prime numbers a lot faster.
[collapse]
Solution
let N = 100
let maxP = 1000
var isPrime: [Bool] = []
var primes: [Int] = []
for i in 0...maxP {
isPrime.append(true)
}
isPrime[0] = false
isPrime[1] = false
for i in 2...maxP {
if isPrime[i] == true {
var j = i*i
while j <= maxP {
isPrime[j] = false
j += i
}
primes.append(i)
}
}
for i in 0..<N {
print(primes[i])
}
[collapse]