Ask coding questions

← Back to all posts
prime number function
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.

Voters
yogeshkumar35
Tmeadows97
CodingGoose
Comments
hotnewtop
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)

CodingGoose

@Roar123

Thanks! :)

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.

CodingGoose

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