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

Java

Prime numbers I understand are not divisible by 2 further I dnt understand the logic but

Can someone explain the logic of this program and how is it working

public boolean isPrimeNumber(int number){

    for(int i=2; i<=number/2; i++){
        if(number % i == 0){
            return false;
        }
    }
    return true;

How the loop will know when to stop

Hi Nirbhay,

In case you're trying to prepare for interview questions, this solution can be further optimized.

You don't have to check past the floor of the square root of the number. This further reduces the number of modulus operations you have to perform.

Take 97 as an example. If you go halfway then you'll do 47 mod operations to find out that 97 is prime. i goes from 2 to 48

If you only go up to the floor of the square root of the number, which is 9, then you only have to do 8 mod operations. i goes from 2 to 9

That's a significant reduction.

1 Answer

Steven Parker
Steven Parker
231,072 Points

:point_right: This is basic logic for testing if a number is prime.

If you try dividing a number by all the numbers between 2 and half of itself, then if any of those divisions have no remainder (the "%" operator), then the number is not prime. You only need to test up to half of itself since no number can be evenly divided by a number larger than half of itself.

Finally, after trying all the potential numbers to divide, if you have not already returned false, then you know you have a prime number and you return true.

Does that clear it up?

Yes surely it does