I have written a program to find whether a number is prime or not.

The program has 2 methods:

  1. take input from user as to the numbers(stored in an array)

  2. take each element of the array and to find whether it is prime or not (this method return type is boolean)

Now my 2nd method is always returning true for all values.

public static boolean Isprime(int x){

    boolean isprime = false;

    for(int m=2;m<x/2;m++){

        int temp = x%m;
        if(temp == 0){
            isprime = false;
        }
        else{
            isprime = true;
        }
    }
    return isprime;
}

Edited:

public static  boolean Isprime(int x){

    boolean isprime = false;

    for(int m=2;m<=x/2;m++){

        int temp = x%m;
        if(temp == 0){
            isprime = false;
            break;
        }
        else{
            isprime = true; 
        }
    }
    return isprime;
}

P.S - It is working for 9 as well.

有帮助吗?

解决方案

You need to break out of for loop as soon as you found if it is not a prime and slighlty modified approach you can follow to omit some code and optimize it as well.

  public static  boolean Isprime(int x){
    boolean isprime = true;

    for(int m=2;m<=Math.sqrt(x);m++){

        int temp = x%m;
        if(temp == 0){
            isprime = false;
            break;
            }
      }
    return isprime;

  }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top