rishi dandu
rishi dandu

Reputation: 1

Using For Loop to Get Prime Numbers java

I have to to get prime numbers using for loop, I have everything and it runs, but it always return "is prime"

Sample Output :

1201 IS PRIME.
77 IS NOT PRIME.
1213 IS PRIME.
88 IS NOT PRIME.
1217 IS PRIME.
99 IS NOT PRIME.
121 IS NOT PRIME.
1431 IS NOT PRIME.
1223 IS PRIME.
141 IS NOT PRIME.
234 IS NOT PRIME.
97 IS PRIME.
436 IS NOT PRIME.
47 IS PRIME.
7 IS PRIME.
547 IS PRIME.
2456 IS NOT PRIME.
34 IS NOT PRIME.

The code:

import static java.lang.System.*;
import java.lang.Math;

public class Prime
{
    private int j;

    private  int result = 0;

    public Prime()
    {
        j = 0;            
    }

    public  Prime(int num)
    {
        j = num;
    }

    public void setPrime(int num)
    {
        j = num;
    }

    //boolean isPrime()   goes here

    public boolean isPrime()
    {           
        boolean prime = true;
        for(int i = 2; i<= j/2; i++)
        {
            if(j % i >= 0)
            {
                prime = false;
            }
            prime = true;
        }
        return prime;            
    }

    public String toString()
    {            
        if( isPrime() == false)
        {
            return "Number: " + j + " is Not Prime.";
        }
        else
        {
            return "Number: " + j + " is Prime. ";
        }           
    }

}

I have the runner set up and I am reading from a file. The problem is that java is not going through the if statement in the back.

Upvotes: 0

Views: 2690

Answers (1)

Eran
Eran

Reputation: 394156

You got your condition wrong.

  if(j % i >= 0)

is always true.

Change it to

  if(j % i == 0)

And remove prime = true; from the loop, otherwise your method will always return true.

Actually, you can get rid of the prime variable and simply return false once you find a divisor :

   public boolean isPrime()
   {
       for(int i = 2; i<= j/2; i++)
       {
          if(j % i == 0)
          {
              return false;
          }
       }
      return true;
   }

Upvotes: 2

Related Questions