Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem with Java Array finding prime numbers

Here is the code

import java.util.Scanner;

public class oneDimensionArray {
    public static void main (String[] args) {
        finding(2,100);
    }
    public static void finding(int start, int end) {
        int[] primeNumbers = new int[end];

        for (int n = start; n < end; n++) {
            boolean check = true;
            int tryNum = 2;
            while (tryNum <= n / 2) {
                if (n % tryNum == 0) {
                    check = false;
                    break;
                }
                tryNum += 1;
            }
            if (check) {
                primeNumbers[n] = n;
            }
        }

        for (int i : primeNumbers) {
            System.out.print(i + ", ");
        }
    }
}

The result successfully shows all prime numbers, but there are a lot of zeros substituting the non-prime numbers, just like this:
0, 0, 2, 3, 0, 5, 0, 7, 0, 0, 0, 11, 0, 13, 0, 0, 0, 17, 0, 19, 0, 0, 0, 23, 0, 0, 0, 0, 0, 29, 0, 31, 0, 0, 0, 0, 0, 37, 0, 0, 0, 41, 0, 43

I wonder where is the problem with my code, and how everything is caused.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should add a variable to store the number of primes found and do this.

public static void finding(int start, int end) {
    int[] primeNumbers = new int[end];

    int count = 0;
    for (int n = start; n < end; n++) {
        boolean check = true;
        int tryNum = 2;
        while (tryNum <= n / 2) {
            if (n % tryNum == 0) {
                check = false;
                break;
            }
            tryNum += 1;
        }
        if (check) {
            primeNumbers[count++] = n;
        }
    }

    for (int i = 0; i < count; ++i) {
        System.out.print(primeNumbers[i] + ", ");
    }
}

output:

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading