Last active
August 29, 2015 14:02
-
-
Save thinkingmedia/210072f01d6235c57174 to your computer and use it in GitHub Desktop.
Find Prime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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
can u please help me understand "return mod > 0;"