简体   繁体   English

计算非质数

[英]Counting non Prime Numbers

I would like to create a method that will return the number of non prime numbers from int array.我想创建一个方法,该方法将从 int 数组中返回非素数的数量。

The method that I use to mark the prime numbers in array look like this(this part don't need any changes):我用来标记数组中素数的方法是这样的(这部分不需要任何更改):

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

I want to modify it so it could return numbers of array[i] = 0 and count it.我想修改它,以便它可以返回 array[i] = 0 的数量并对其进行计数。

I went this far by adding a HashMap:我通过添加一个 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);
    }

In general I am close but I don't know how to remove all index from Map that is above 1. It already calculate the amount of 0 on first index.一般来说,我很接近,但我不知道如何从 Map 中删除所有高于 1 的索引。它已经计算了第一个索引的 0 数量。

Here is my solution approach.这是我的解决方法。

1) First crete a very simple method to check whether a number is prime or not. 1)首先给出一个非常简单的方法来检查一个数是否为素数。 See below:见下文:

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) Create another method that will loop through your array and call the above method: 2)创建另一个方法来循环遍历您的数组并调用上述方法:

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

3) Then simply call this from your main method: 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);
}

If I did not make any mistake when writing this shoul give you the number of non primes in your array.如果我在写这篇文章时没有犯任何错误,应该给你数组中非素数的数量。

Your method for calculating the prime numbers was not correct and hence your count was not coming correct.您计算素数的方法不正确,因此您的计数不正确。 You approach to count the number of non prime numbers was almost on point.您计算非质数数量的方法几乎是正确的。

I have modified the code a bit to work correctly here我稍微修改了代码以在此处正常工作

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");
        }
    }

One of the best ways to do this is to keep a running list of primes and then check the list.最好的方法之一是保留一个正在运行的素数列表,然后检查该列表。 The first part is driver code so it needs no explanation.第一部分是驱动程序代码,无需解释。

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

Here is the start of the prime lookup method.这是素数查找方法的开始。 Key points are as follows:要点如下:

  1. It uses a LinkedHashSet to store the primes.它使用LinkedHashSet来存储素数。
    a.一种。 It maintains order.它维持秩序。
    b.Allows for quick lookup for a specific value允许快速查找特定值

  2. It finds all the primes up to the submitted value and stores them.它找到所有质数直到提交的值并存储它们。 This is only done if the submitted value is greater than than last prime recorded.仅当提交的值大于记录的最后一个素数时才会这样做。

  3. The subsequent candidate primes start with the last prime recorded + 2. Since all primes after 2 are odd, this is also guaranteed to be the next odd value.随后的候选素数从记录的最后一个素数 + 2 开始。由于 2 之后的所有素数都是奇数,因此这也保证是下一个奇数。 Candidates are incremented by 2 to skip even numbers.候选人增加 2 以跳过偶数。

  4. to detect if a candidate is prime, division by previously recorded primes is done (but only up to the square root of the candidate).为了检测一个候选者是否是素数,除以之前记录的素数(但只能达到候选者的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