简体   繁体   中英

Java 2d Array Matrix Program(Sum of Prime Numbers)

for(i=2;i<=5;i++) {
        for(j=2;j<=(i/2);j++) {
            if(i%j== 0) {
                j=i;
                break;
            }
        }
        if(i!=j) {
            sum +=i;            
        }
    }
    System.out.println("The sum of all prime numbers is : "+sum);

What I'm trying to achieve is the sum of all prime numbers when I run my program, i am using this code but then the sum is not what I think it is. The sum is greater than what I expected it. I tried rewriting and changing some but the result is as is. Other informations: The matrix is randomized from 0-9, it is a (5x5)2D array.

You should take into account the specific requirement that array elements are randomized from 0 to 9, thus you have to check for the following primes below 10: [2, 3, 5, 7].

Then iterate the matrix and sum up all primes:

private static boolean isPrimeBelow10(int x) {
    return x == 2 || x == 3 || x == 5 || x == 7;
}

public static int sumPrimes(int[][] arr) {
    int sum = 0;
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr[i].length; j++) {
            if (isPrimeBelow10(arr[i][j])) {
                sum += arr[i][j];
            }
        }
    }
}

If you needed to handle larger elements, then you would have to maintain an extendable list of primes and add new elements to it as necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM