Home > OS >  Problem with Java Array finding prime numbers
Problem with Java Array finding prime numbers

Time:11-20

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.

CodePudding user response:

Why you take new array it's allocate memory space...

public class MyClass {
   public static void main (String[] args) {
        finding(100);
    }
    
    public static void finding(int end) {
    int count = 0;
    for (int n = 2; n < end; n  ) {
        count = 0;
        int tryNum = 1;
        while (tryNum <= n) {
            if (n % tryNum == 0) {
                count  ;
            }
            tryNum  ;
        }
        
        if(count==2)
           System.out.print(n "  ");     
        }
    }
}

CodePudding user response:

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, 

CodePudding user response:

In java, every cell in an int array is initialled to 0, so when you print the array the output is indeed, bunch of zeros. to fix it, you can use a simple if statement to check of the value of a cell is not 0 like that:

for (int i : primeNumbers) {
   if (i != 0) {
     System.out.println(i   ", ");
   }
}
  •  Tags:  
  • java
  • Related