java中的素数测试

时间:2014-03-02 22:05:59

标签: java

public static boolean isPrime(int number)
{
  boolean result = true;

  for (int i=2; i < number/2; i++)
  {
     if (number%i == 0)
     {
        result = false;
     }
  }

  return result;
}

这段代码有效,但是如何修改它,以便当int number = 0时,它返回false?当number = 0时,它返回true。

2 个答案:

答案 0 :(得分:8)

是的,它看起来很简单:)

public static boolean isPrime(int number) {
    boolean result = true;
    if (number == 0){
        return false;
    }

    for (int i = 2; i < number / 2; i++) {
        if (number % i == 0) {
            result = false;
        }
    }

    return result;
}

有效的方法是:

public static boolean isPrime(int number) {
    //Everything less or equal 1 is not prime number
    if (number <= 1) {
        return false;
    }

    //2 is very special case, so I check it separately
    if (number == 2) {
        return true;
    }

    //This will help me rid off all even numbers
    if (number % 2 == 0) {
        return false;
    }


    //It is important to count the sqrt before using it in for-loop condition.
    //If you use it in for-loop condition, it will be counted every single iteration.
    int square = (int) Math.sqrt(number);

    //I already checked %2, so now I need to check only odd numbers
    for (int i = 3; i <= square; i += 2) {
        if (number % i == 0) {
            //If I find one number, I do not have to continue
            return false;
        }
    }
    return true;
}

答案 1 :(得分:0)

public static boolean isPrime(int number) {

    if (number < 2){
        return false;
    }

    for (int i = 2; i < number / 2; i++) {
        if (number % i == 0) {
            return false;
        }
    }

    return true;
}