簡體   English   中英

創建返回數組中素數個數的方法時遇到麻煩

[英]trouble creating a method that returns the number of prime integers in the array

我在創建一種方法時會遇到麻煩,該方法可以找出數組中素數的數量,到目前為止,我已經做到了,但是當我運行它時,它不能正常工作,它會將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;

}

}

if (numbers[i] % 3 == 0)確定素數絕對是錯誤的。 首先,您需要知道什么是質數 (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;
}

您要驗證的條件僅返回不能被3整除的數字,以查找至少需要檢查所有小於平方根的數字的質數。 即。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM