簡體   English   中英

計算非質數

[英]Counting non Prime Numbers

我想創建一個方法,該方法將從 int 數組中返回非素數的數量。

我用來標記數組中素數的方法是這樣的(這部分不需要任何更改):

public static int markNonePrimeNumbers(int[] array) {
        createInitialArray(100);
        for (int j = 2; j < array.length; j++) {
            for (int i = j * 2; i < array.length; i += j) {
                array[i] = 0;
            }
        }

我想修改它,以便它可以返回 array[i] = 0 的數量並對其進行計數。

我通過添加一個 HashMap 做到了這一點:

public static int[] markNonePrimeNumbers(int[] array) {
    createInitialArray(100);
    for (int j = 2; j < array.length; j++) {
        for (int i = j * 2; i < array.length; i += j) {
            array[i] = 0;
        }
    }
    Map<Integer, Integer> map = new HashMap<>();
    for (int key : array) {
        if (map.containsKey(key)) {
            int occurrence = map.get(key);
            occurrence++;
            map.put(key, occurrence);
        } else {
            map.put(key, 0);
        }
    }
    for (Integer key : map.keySet()) {
        int occurrence = map.get(key);
        System.out.println(occurrence);
    }

一般來說,我很接近,但我不知道如何從 Map 中刪除所有高於 1 的索引。它已經計算了第一個索引的 0 數量。

這是我的解決方法。

1)首先給出一個非常簡單的方法來檢查一個數是否為素數。 見下文:

public static boolean checkPrime(int number) {
    if (number <= 1) {
        return false;
    }
    System.out.println(number);

    for (int i=2; i <= Math.sqrt(number); i++) {
        if(number % i == 0) {
            System.out.println(i);
            return false;
        } 
    }
    return true;

}

2)創建另一個方法來循環遍歷您的數組並調用上述方法:

public static int numOfPrimesInArray(int[] arr){
    int counter = 0;
    for (int num: arr){
        if (!checkPrime(num)) counter++;
    }
    return counter;
}

3)然后只需從您的主要方法中調用它:

public static void main(String[] args){
    int[] nums = {1,2,3,5,6,7,8,9,10};
    int nonprimes = numOfPrimesInArray(nums);
    System.out.println(nonprimes);
}

如果我在寫這篇文章時沒有犯任何錯誤,應該給你數組中非素數的數量。

您計算素數的方法不正確,因此您的計數不正確。 您計算非質數數量的方法幾乎是正確的。

我稍微修改了代碼以在此處正常工作

public static void main(String[] args){

        int[] array = new int[]{1,2,3,4,57,10,7,11,13,17,16};
        for (int i = 0; i < array.length; i++) {
            int temp = 0;
            for(int j=2;j<=array[i]/2;j++)
            {
                temp=array[i]%j;
                if(temp==0)
                {
                    array[i] = 0;
                    break;
                }
            }
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int key : array) {
            if (map.containsKey(key)) {
                int occurrence = map.get(key);
                occurrence++;
                map.put(key, occurrence);
            } else {
                map.put(key, 1);
            }
        }
        if(map.containsKey(0)){
            System.out.println(map.get(0));
        } else {
            System.out.println("could not find");
        }
    }

最好的方法之一是保留一個正在運行的素數列表,然后檢查該列表。 第一部分是驅動程序代碼,無需解釋。

        int[] array = new int[] { 1,19, 2, 3, 4, 57, 10, 7, 11,
                13, 17, 16 };
        List<Integer> nonPrimes = new ArrayList<>();
        for (int c : array) {
            if (!isPrime(c)) {
                nonPrimes.add(c);
            }
        }
        System.out.println(nonPrimes);

這是素數查找方法的開始。 要點如下:

  1. 它使用LinkedHashSet來存儲素數。
    一種。 它維持秩序。
    允許快速查找特定值

  2. 它找到所有質數直到提交的值並存儲它們。 僅當提交的值大於記錄的最后一個素數時才會這樣做。

  3. 隨后的候選素數從記錄的最后一個素數 + 2 開始。由於 2 之后的所有素數都是奇數,因此這也保證是下一個奇數。 候選人增加 2 以跳過偶數。

  4. 為了檢測一個候選者是否是素數,除以之前記錄的素數(但只能達到候選者的square root )。

    static Set<Integer> primes = new LinkedHashSet<>() {
        {   // seed the first two primes.
            add(2);
            add(3);
        }
    };

    // last recorded prime
    static int lastPrime = 3;

    public static boolean isPrime(int val) {
        for (int candidate = lastPrime+2; candidate <= val; candidate += 2) {
           int max = (int)(Math.sqrt(candidate)) + 1;
            for (int p : primes) {
                // if candidate is divisible by any prime, then discontinue
                // testing and move on to next candidate via outer loop
                if (candidate % p == 0) {
                    break;
                }
                // if the limit has been reached, then a prime has been
                // found, so add to list of primes and continue with
                // next candidate.  Only check up tot he square root of the candidate.
                if (p >= max) {
                    // add new found prime to list
                    primes.add(candidate);
                    lastPrime = candidate;
                    break;
                }
            }
        }
        // Now check the newly built (if required) hash set to see if the passed value
        // is in the list.
        return primes.contains(val);
    }

暫無
暫無

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

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