The compiler is confused because both return statements are conditional. It isn't sure any one of them will happen. Your program will compile if you simply move the return true;
outside the for loop.
class Main
{
static boolean isPrime(int x)
{
for(int i = 2;i <= x/2;++i)
{
if(x%i == 0)
{
return false;
}
}
return true;
}
public static void main (String args[])
{
boolean prime = isPrime(11);
System.out.println(prime);
}
}
Your program will not return a correct answer fo x <= 2
. We can fix that by adding a few ifs at the beginning.
class Main
{
static boolean isPrime(int x)
{
if (x < 2)
{
return false;
}
if (x == 2)
{
return true;
}
for(int i = 2;i <= x/2;++i)
{
if(x%i == 0)
{
return false;
}
}
return true;
}
public static void main (String args[])
{
boolean prime = isPrime(11);
System.out.println(prime);
}
}
You can improve the performance of your program without too much of a change by limiting your search to sqrt(x)
instead of x/2
. And now that we are optimising, we might as well only check the odd numbers.
class Main
{
static boolean isPrime(int x)
{
if (x < 2)
{
return false;
}
if (x == 2)
{
return true;
}
if (x % 2 == 0)
{
return false;
}
int limit = (int) Math.sqrt(x);
for(int i = 3; i <= limit; i += 2)
{
if(x%i == 0)
{
return false;
}
}
return true;
}
public static void main (String args[])
{
boolean prime = isPrime(11);
System.out.println(prime);
}
}