简体   繁体   中英

find prime number using while loop in java

I wanna find prime numbers. It divides n by all numbers between 2 and (n–1) , but it is wrong somewhere. For example 9 , it gives true .

Appreciate any help.

public void isPrime(int n) {

    int i = 2;
    while (i <= (n - 1)) {
        if (n % i == 0) {
            System.out.println("It's not a prime number");
            break;
        } else {
            System.out.println("It's a prime number");
            break;
        }
        i++;
    }
}

The statement i++ is unreachable, so you don't want the else{...} to contain break . Instead, you simply want else i++ .

Where you want the "is prime" statement is outside the loop, since you don't know n is prime until the loop finishes checking all the divisors.

And you don't want break inside the if ; you want return , because otherwise it'll print "is prime".

PS You can make the while say while(i < Math.sqrt(n)) to reduce iterations (think about it).

EDIT

You might want to make the return type boolean instead of printing messages, putting return false if there's a divisor and return true if there was no divisor.

this method will return a boolean if your number is prime or not. In the for loop you can see that we first test 2. If our number isn't divisible by two then we don't have to test any even numbers. This is a very efficient way to test for prime numbers.

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

Here's the code for prime number,

import java.util.Scanner;

public class JavaPrimeNumber 
{
   public static void main(String[] args) 
   { 
      boolean checkPrime = true;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter any number find prime number in java : "); 
      int number = sc.nextInt();

      int a = 2;
      while(a <= number / 2)
      {
         if(number % a == 0)
         {
            checkPrime = false;
            break;
         }
         a++;
      }

      if(checkPrime)
         System.out.println(number + " is a prime number.");
      else
         System.out.println(number + " is not a prime number.");
      sc.close();
   }
}

The problem is that you break out of the loop on the first check: you divide by 2 and report the answer based only on that.

Restructure your loop so that the decision "It's a prime number" is delayed until you get all the way through the loop. You may want to set a boolean variable for this.

Also, I recommend using a for loop, since you know the maximum number of times you'll iterate. Note that you don't have to go to n-1, just to sqrt(n).

public void isPrime(int n) {
    if(n % 2 == 0) {
       System.out.println("It is not a prime number");
       return;
    }   
    else {
       int i = 3;
       while(i <= Math.sqrt(n) ) {
           if( (n % i) == 0) {
              System.out.println("It is not a prime number");
              return;
           }
           i = i + 2; 
       }
    }
    System.out.println("It is a prime number");
    return;

}

You can do the while loop in this way, first you want to check if no is divisible by 2, if so it is not a prime number. If not check for odd nos till square root of n. Dont need to check for even, if no is not divisible by 2 it will not be divisible by any even number.

//import java.util.*;
import java.util.Scanner;
class Primenos
{   public static void main(String args[])
    {   int no, flag = 0, a, b;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any no: ");
        no = sc.nextInt();
        a=1;
        while(a<=no)
        {
            flag=0;
            b=2;
            while(b<=a>>1)
            {
                if(a%b==0)
                {   flag = 1;
                    break;
                }
                b++;
            }
            if(flag==0)
            {   System.out.println("Prime number" + a);
            }
            else
            {   System.out.println("Not Prime number" + a);
            }
            a++;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM