I have written a function which currently displays all of the prime numbers under 1000.
I can keep making 1000 bigger to generate more numbers, but I do not know how to make it keep going on forever once run.
func generatePrimes() {
let numbers = 2...1000
for n in numbers {
var prime = true
for i in 2..<n {
if n % i == 0 {
prime = false
break
}
}
if prime == true {
print(n)
}
}
}
You could use a while
loop with the argument being true
. That way, the loop would never end.
func generatePrimes() {
var n = 2
while true {
var prime = true
for i in 2..<n {
if n % i == 0 {
prime = false
break
}
}
if prime == true {
print(n)
}
n += 1
}
}
Note that we use a variable ( n
) and increment (add 1 to it) on each iteration of the while loop.
If you want it to end when it hits some n
, you can have a conditional that checks against n
and break
's out of the loop:
var n = 2
while true {
if n == 1000 {
break
}
n += 1
}
The above code will stop execution when n
hits 1000
and will not print anything for that case.
Use a while
loop instead of for
loop. It can also be done with a for
loop, but for
loop is preferred when you know the number or range of the iterations you are performing. If you're using a while loop you just have to set the condition for the loop, in this case you need to specify the condition as true since you want the loop to run forever.
Just replace your for
loop in your code with while
. It should look something like this
while(true)
{
if n % i == 0 {
prime = false
break
}
}
You also can build an unconditional infinite loop using do {}
block and continue
statement.
AGAIN:
do {
print("step...")
continue AGAIN
}
func generatePrimes() {
var prime = true
let numbers = 2...1000
for n in numbers {
prime = true
if n == 2 || n == 3 {
print(n)
} else {
for i in 2..<n-1 {
if n % i == 0 {
//not prime numbers
prime = false
}
}
if prime == true {
print(n)
}
}
}
}
You can do it like this. Just exclude 1 and n.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.