-1

I am trying to write a code to check if a number is prime and return true if it is a prime number using if/else statement.

I am giving the code below, I have written. It is always showing an exception "missing return statement".

class Main
{
    static boolean isPrime(int x)
    {
        for(int i = 2;i <= x/2;++i)
        {     
            if(x%i == 0)
            {
                return false;
            }
            else
            {
                return true;
            }   
        }
    }

    public static void main (String args[])
    {              
        boolean prime = isPrime(11);
        System.out.println(prime);           
    }
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
Gaurav Kumar
  • 97
  • 1
  • 7
  • I want to check if it is a prime. – Gaurav Kumar Jan 30 '21 at 13:47
  • Please excuse me for leaving other logics. – Gaurav Kumar Jan 30 '21 at 13:48
  • Why not just ``return (x % i) == 0;`` – NomadMaker Jan 30 '21 at 14:02
  • 2
    There are odd cases where the for-loop doesn't run. The compiler wants a return at the end. – NomadMaker Jan 30 '21 at 14:04
  • Hint: `if(condition) { return true; } else { return false; }` is same as `return condition;`. So your loop looks like `for(int i = 2;i <= x/2;++i) { return x%i == 0; }` which defeats the purpose of loop as you are always returning some value in the first iteration, which prevents other iterations). Try to think more about each of your if/else branches. Are you really able to return correct value in each of them? Maybe some value can be returned only after all iterations will check their conditions? – Pshemo Jan 30 '21 at 14:06

8 Answers8

3

The problem in your code is that you are returning true the first time the modulus is not 0. That's wrong, because you have to make sure that x is not divisible to any of the numbers in range [2, x/2].

Modify your method as follows:

static boolean isPrime(int x)
{
    if(x <= 1)
    {
        return false;
    }

    boolean ret = true;

    for(int i = 2;i <= x/2;++i)
    { 
         if(x%i == 0)
         {
              ret = false;
              break;
         }           
     }

     return  ret;
 }

In this way you break as soon as you are sure the number is not prime. If it's prime it will complete the loop without finding non-zero remainders.

The x<=1 scenarios is the cause of the warning you are experincing, as with those inputs your method exits without encountering a return statement. I just checked for this condition at the beginning of the function.


Finding prime numbers

I just suggested the fix to your isPrime implementation, which is the simpliest way to find prime numbers. Anyway there are smarter ways to find them:

  • The Siege of Eratosthenes method
  • You could check only odd numbers, saving half the time
  • You could check if x belongs to the 6*x±1 set. In fact all prime numbers from number 5 follow this rule
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
2

You are not taking into account that the number "x" passed into the method can be zero. If that is the case (x == 0) you loop will not execute and there is a path through the method that does not return TRUE or FALSE.

2

As explained before, in the existing implementation it is possible that loop is not executed and no return statement is provided after the loop.

Better search for prime numbers would be:

  1. Check for 0 and 1 to return false for them
  2. Check for even numbers: all even numbers except 2 are composite
  3. Check only odd numbers for primality
  4. Check limited range of numbers using "inverse" square root condition: i * i <= n
  5. (Optionally) Exclude negative numbers

Example implementation:

static boolean isPrime(int x) {
    int n = Math.abs(x); // exclude negatives
    
    if (n < 2) return false;        // exclude 0, 1
    if (n % 2 == 0) return n == 2;  // exclude even except 2
     
    for (int i = 3; i * i <= n; i += 2) {  // check only odd numbers
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

Faster implementation using 6n ± 1 rule (thanks Roberto Caboni) could look like this (starting from 5 (6n - 1) and using variable steps 2 and 4):

static boolean isPrimeFaster(int x) {
    int n = Math.abs(x);
    
    if (n < 2) return false;       // exclude 0, 1
    if (n % 2 == 0) return n == 2; // exclude even except 2
    if (n % 3 == 0) return n == 3; // exclude multiples of 3

    for (int i = 5, j = 2; i * i <= n; i += j, j = j == 2 ? 4 : 2) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
0

Use a boolean variable and set it true when the number is divisible. Also check if the number is less than 2 because one and zero are not primes so return false then.

The problem in your code currently is that you immediately return false or true after the first iteration but you have to check as long as you found a divisor or you run up from 2 until the square root of x This is more accurate to run until the iterator is less or equal than the square root of the prime

If you are interested why to use the square root as running condition check out this answer


public static void main(String[] args) {
    
System.out.println(isPrime(0));
System.out.println(isPrime(3));
System.out.println(isPrime(4));
System.out.println(isPrime(5));
System.out.println(isPrime(11));
}

public static boolean isPrime(int x) {
    boolean isPrime = true;; 
    
    if(x < 2) {
        return false;
    }
    for(int i = 2; i <= Math.sqrt(x); i++) {
        if (x % i == 0) {
            isPrime = false;
            break;
        } 
    }
    
    return isPrime;

 }

Generates the output

false
true
false
true
true
Aalexander
  • 4,987
  • 3
  • 11
  • 34
0

You need this implementation

static boolean isPrime(int x)
{
    If(x==0||x==1) {
          return false;
     }
    for(int i = 2;i <= x/2;++i)
    {     
        if(x%i == 0)
        {
            return false;
        }
     }
     return true;
}
Jugal
  • 68
  • 7
0

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);
    }
}
Kristof Neirynck
  • 3,934
  • 1
  • 33
  • 47
-1

java compiler expects isPrime() always returns a boolean.
you can loop and when remaining become 0 return false. and after and loop return true.

static boolean isPrime(int x)
    {
        for(int i = 2;i <= x/2;++i)
            if(x%i == 0)
                return false;
        return true;
    }
-3

class PrimeNumber {

   static boolean isPrime(int x)
       {

           boolean status = false;
            for(int i = 2;i <= x/2;++i)
            {

                if(x%i == 0)
                {
                  status = false;
                }
                else
                {
                 status = true;
                }
            }

         return status;
    }

   public static void main (String args[])
   {
       boolean prime = isPrime(11);
       System.out.println(prime);
   }

}

this will solve your problem