Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Raghavendra Temkar
Raghavendra Temkar
677 Points

how to find a set of prime numbers in a range

I would like to find out what numbers are prime in a given set ... say numbers between 1 and 20. So prime numbers are not divisible by any other number except the number itself.

so for numbers between 1 and 20, i need to check if the number is divisible by any number in the given range. I use this code but it is not working

var x = 1
var i = 1
while x <= 20 {

    if ((20 - i) % x  == 0) {

        print("\(x) is not a prime number")
}
    x += 1

}

1 Answer

Jeff McDivitt
Jeff McDivitt
23,970 Points

One way you could do it is by using a for in statement

for number in 1...20 {

    if number % 2 != 0 {
        print("\(number) I am not a prime number")
    }
}
Raghavendra Temkar
Raghavendra Temkar
677 Points

this will only tell me if. number is even or odd, not whether its a prime number