Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@thinkingmedia
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkingmedia/210072f01d6235c57174 to your computer and use it in GitHub Desktop.
Save thinkingmedia/210072f01d6235c57174 to your computer and use it in GitHub Desktop.
Find Prime
public boolean isPrime(int n)
{
int divisor = 2;
int limit = n-1 ;
if (n == 2)
{
return true;
}
int mod = 0;
while (divisor <= limit)
{
mod = n % divisor;
if (mod == 0)
{
return false;
}
divisor++;
}
return mod > 0;
}
@javascript-uk
Copy link

can u please help me understand "return mod > 0;"

@thinkingmedia
Copy link
Author

Hi,

In your original code you had this.

if (n == 2)
{                  
    return true;
}
else
{
      //.....
}
return false;

The else condition is not required because the cursor inside if(n==2) will exit the function.

That changes the code to this.

if (n == 2)
{                  
    return true;
}

int mod = 0;
while (divisor <= limit)
{
    mod = n % divisor;
    if (mod == 0)
    {
        return false;
    }
    divisor++;
}

if (mod > 0)
{
    return true;
}

return false;

Now the code at the bottom. The if (mod > 0) can be reduced to a return statement of just return mod > 0;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment