Skip to content
Sign upLog in

prime number function

Profile icon

I am trying to create a function that prints prime numbers up to a certain limit that you type in. For example, if you pass in 100, the function should print the prime numbers between 1 and 100.

A number is prime if it is only evenly divisible by itself and 1, and not evenly divisible by any other number.

So far, this code just prints even numbers as prime and odd as not prime. I feel like I am missing a big chunk of code to check for other conditions but I'm not sure what.

func printPrimes(upTo n: Int){ for x in 1...n { if x % 2 == 0 { print("\(x) is a prime number") } else { print("\(x) is not a prime number.") } } } printPrimes(upTo: 100)
You are viewing a single comment. View All
Profile icon

has a good explanation so check that out. If you want a prime number challenge, check out the Sieve of Eratosthenes (explanation and example)

Profile icon


Thanks! :)