-12
public static void isPrime(int number)
{
    for ( int i = 2; i<number ; i ++)
    {
      if ( number%i!=0 ) {
        System.out.println(number + " is not a prime ");
      }
      else
      {
        System.out.println(number +" is  a prime ");
      }
    }

and the results is :

60 is a prime
60 is not a prime
60 is not a prime
60 is a prime
60 is not a prime
60 is not a prime
60 is not a prime
60 is not a prime
60 is a prime
60 is not a prime
60 is not a prime
60 is not a prime
60 is not a prime
60 is not a prime
60 is not a prime
60 is not a prime

All I want is whether it's a prime or not; in this case it isn't.

nbrooks
  • 18,126
  • 5
  • 54
  • 66
  • 2
    Indent your code properly and you should see problem better. – Pshemo Nov 06 '16 at 18:24
  • You're just performing one check per number and immediately saying a number is a prime if you can divide it by `i` (instead of checking all of the other `i` as well) – Keiwan Nov 06 '16 at 18:26
  • 2
    Also try to explain your algorithm. What makes you think it should give different results then what you are getting now? – Pshemo Nov 06 '16 at 18:29
  • 1
    Why the down vote? – develop1 Nov 06 '16 at 18:37
  • All of the other issues in your code aside, it's not necessary to have your `for` loop run from 2 to `n`. You can stop at `sqrt(n)`. In every pair of factors of `n`, one of them will be less than or equal to `sqrt(n)`. Have a look at this [proof](http://stackoverflow.com/a/5811176/803925). – nbrooks Nov 06 '16 at 18:43
  • 1
    Possible duplicate of [How to determine if a number is prime](http://stackoverflow.com/questions/40199440/how-to-determine-if-a-number-is-prime) – nbrooks Nov 06 '16 at 19:00
  • Only print the result once you know the final outcome, don't print it every time inside the loop. BTW you only need to check 2 and odd numbers up to the square root of the number tested. – Peter Lawrey Nov 06 '16 at 19:18
  • yall are merciless. crushing the poor soul with at least 13 downvotes – Ungeheuer Nov 09 '16 at 21:23

1 Answers1

2

You are missing a bracket. If you keep your code clean it will solve the problem.

Also in your if statement you are checking if number % 2 != 0. If it does not equal to 0 then it could potentially be a prime number. So I changed it to number % 2 == 0 to fix the problem.

The other mistake is that you kept printing even after you knew that the number is not prime.

public static void isPrime(int number)
    {
        for ( int i = 2; i<Math.sqrt(number) + 1; i ++)
        {
            if ( number%i==0 ) {//If number is not a prime
                //Will print that the number is not a prime once
                System.out.println(number +" is not a prime number.");
                return ; //Will exit the method
            }
        }
        //If you reach this point then the number is prime.
        System.out.println(number +" is a prime number.");
    }
develop1
  • 747
  • 1
  • 10
  • 32