Skip to content
← Back to Community
prime number function
Profile icon
Tmeadows97

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)
Voters
Profile icon
lilypeter
Profile icon
yogeshkumar35
Profile icon
Tmeadows97
Profile icon
CodingGoose
Comments
hotnewtop
Profile icon
FulopCyborg011101

THANK YOU, you saved my grade!!!!!!!!!

Profile icon
Roar123

@DannyIsCoding 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
CodingGoose

@Roar123

Thanks! :)

Profile icon
CodingGoose

Hi! I don't code swift.
You need first to make a function to check if a number is prime. You can do that using a loop where you have a num = 2 that is getting bigger by one every time. If the number you want to check that is prime % num is not 0, then the number is prime. If the rest of the division between the number to check and num isn't 0, then it's prime.

Then you need a blank list to store all the primes. You then have to make a loop. In then loop you check if num2 is prime (using the function before). If it is, you add it to the list. Else, you don't. num2 is getting bigger by one every time.

Sorry if it is confusing. I don't code this language, I use python. I tried to explain it as good as I could.

Profile icon
CodingGoose

@DannyIsCoding Also if this was helpful, i don't mind marking my answer as correct ;)