简体   繁体   English

程序不打印矩阵中素数的正确总和值

[英]Program does not print the correct sum value of prime numbers in a matrix

I am a beginner in the java language.我是 java 语言的初学者。 I was tasked to create a matrix that calculates the total sum of all prime numbers from the randomly-generated numbers present in the matrix.我的任务是创建一个矩阵,该矩阵根据矩阵中随机生成的数字计算所有素数的总和。 However, my program does not print the correct value at all.但是,我的程序根本没有打印正确的值。 What seems to be the problem with my code?我的代码似乎有什么问题?

public static void main(String[] args) {
    int arr[][] = new int[5][5];
    Random ran = new Random();

    System.out.println("Print matrix");
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr.length; j++) {
            arr[i][j] = 10 + ran.nextInt(50 - 10 + 1);
            System.out.print(arr[i][j] + "\t");
        }
        System.out.println();
    }
    int sum = 0;
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr.length; j++) {
            int num = 0;
            for (int k = 1; k <= arr[i][j]; ++k)
                if (arr[i][j] % k == 0)
                    num++;
            if (num == 2)
                sum = sum + arr[i][j];
        }
    }
    System.out.println("\nPrint the sum of prime no. in the matrix: " + sum);
}

Output: Output:

Print matrix
33  11  41  43  38  
32  18  25  16  24  
40  16  11  18  11  
49  37  22  13  17  
10  45  30  13  37  

Print the sum of prime no. in the matrix: 234

The correct sum value should be 283 instead of 234 .正确的总和值应该是283而不是234

49 is not prime = 7 * 7 = 49 49 不是素数 = 7 * 7 = 49

For the input in the question, 234 is correct answer.对于问题中的输入, 234是正确答案。 11 + 41 + 43 + 11 + 11 + 37 + 13 + 17 + 13 + 37

For the input in the image, expected result is correct 11 + 47 + 19 + 17 + 41 + 29 + 37 = 201对于图像中的输入,预期结果是正确的11 + 47 + 19 + 17 + 41 + 29 + 37 = 201

Possible correction可能的修正

  1. Unless the matrix is a square matrix, it better to use the inner loop as j < arr[i].length除非矩阵是方阵,否则最好使用内循环为j < arr[i].length
  2. Prime number check requires division only till floor(sqrt(num))质数检查只需要除法直到floor(sqrt(num))

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

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