创建一个返回数组中素数整数的方法时遇到问题

时间:2014-12-09 05:26:14

标签: java arrays methods integer

我无法创建一个方法来查找数组中的素数整数,到目前为止我已经完成了这个但是当我运行它时,它没有正常工作它将2作为素数并且还有其他数字。有什么建议吗?

    int[] newSet = {8, 4, 22, 82, 12, 32, 18, 400, 3, 33, 401, -1, 1, 3, 9};
    System.out.println(primeIntegers(newSet));

}

public static int primeIntegers(int[] numbers) {
    int count = 0;
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] % 3 == 0) {
            count++;
        }

    }

    return count;

}

}

2 个答案:

答案 0 :(得分:2)

if (numbers[i] % 3 == 0)肯定是错误的确定素数。首先,您需要知道prime number是什么(2是素数)。

确定数字是否为素数的最简单(不是最好)的方法是:

//checks whether an int is prime or not.
boolean static  isPrime(int n) {
    for(int i=2;i<n;i++) {//here,change i<n into 2*i<n or  Math.sqrt(i)<n will be better
        if(n%i==0)
            return false;//can be dividable by not one or itself.
    }
    return true;
}

//use above method to count the prime number
public static int primeIntegers(int[] numbers) {
    int count = 0;
    for (int i = 0; i < numbers.length; i++) {
        if(isPrime(numbers[i]))
            count++;
        }
    }
    return count;
}

答案 1 :(得分:0)

您正在验证的条件仅返回不能被3整除的数字,以便找到您需要的素数,以至少检查小于其平方根的所有数字。 即

boolean chkPrime(int num)
{
    for(int i=2;i<(sqrt(num));i++)
        if(num % i==0)
            return false;
    return true;
}