简体   繁体   中英

Java seperate method to find Prime numbers

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 2 nd 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;
}

PS - 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;

  }

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