简体   繁体   English

Java 2d Array Matrix Program(素数之和)

[英]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.其他信息:矩阵从 0-9 随机化,它是一个 (5x5)2D 数组。

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].您应该考虑数组元素从 0 到 9 随机化的具体要求,因此您必须检查以下 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.如果您需要处理较大的元素,则必须维护一个可扩展的素数列表,并根据需要向其中添加新元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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