Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining Prime Numbers Java

Tags:

java

I am writing a program that takes as input an integer, and outputs a message whether the integer entered is prime or not. The algorithm I am using is as follows... Require: n>0, Require: isPrime <- true, for i=2 to sqrt(n) do, if n%i=0 then isPrime <- false end if and end for Then Print whether the number is Prime or not. Here is my code so far, the code is not working and I am not able to find the problem.

     public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    int n;
    System.out.println("Input a positive integer");
    n = kb.nextInt();

        while (n>0){
            boolean isPrime = true;
            for (int i =2; i <= n/2;i++){
                if(n % i == 0){
                    isPrime = false;
                    break;
                }
            }
            if (isPrime = true){
                System.out.println("The integer, " + n + ", is a prime");
                break;
            }
            else{
                System.out.println("The integer, " + n + ", is not a prime");
                break;
            }
        }
    }
}

I would be grateful if someone could help, Thanks!

like image 726
CBH Avatar asked Jul 12 '26 15:07

CBH


1 Answers

Your problem lies with this line:

if (isPrime = true){

You made an assignment, instead of comparing to true, so the statement is always true.

Use == to compare boolean values, or better yet, since isPrime is already a boolean:

if (isPrime){
like image 86
rgettman Avatar answered Jul 15 '26 04:07

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!