Mysterious Square

1
  

The whole numbers positioned in a square NxN such that all lines and main diagonal have the same sum.

     

For example, the square below

2 7 11
9 5 6
4 3 13
     

is a mysterious square of sum 20, since all lines (2 + 7 + 11 = 20, 9 + 5 + 6 = 20 and 4 + 3 + 13 = 20) 20) have the same sum (20).

     

Write a program that, given a square, determines whether it is mysterious or not and what its sum (if it is magical).

     

Entry

     

The first line contains an integer N. The next N lines contain N integers each, separated by exactly one whitespace.

     

Output

     

Your program should print a single line with an integer representing the sum of the magic square or -1 if the square is not magic.

PS: I can not use vector, I can only use repetition structures.

  

EXAMPLE 1

     

ENTRY:

3
2 7 11
9 5 6
4 3 13
     

OUTPUT:

20

PS: My output was:

  

-1

Here is my code:

int main()
{
    int n, i, j, elem;
    int , soma_linhas = 0, soma_dp = 0;

    scanf("%d", &n);


    //leitura dos elementos
    for(i = 0; i < n; i++){
        for(j = 0; j < n; j++){
            scanf("%d", &elem);
            //somatorio de cada linha
            aux += i;
            soma_linhas = aux;
        }
    }

    //somatorio da diagonal principal 
    for(i = 0; i < n; i++){
        for(j = 0; j < n; j++){
            if(i == j){
                aux += i + j;
                soma_dp = aux;
            }
        }   
    }

    if(soma_linhas == soma_dp)
        printf("%d", soma_linhas);//se for quadrado misterioso tanto faz mostra a linhas ou da diagonal 
    else
        printf("-1");
    return 0;
}

Where am I going wrong?

    
asked by anonymous 03.07.2018 / 06:34

2 answers

6

Let's look at these links:

//leitura dos elementos
for(i = 0; i < n; i++){
    for(j = 0; j < n; j++){
        scanf("%d", &elem);
        //somatorio de cada linha
        aux += i;
        soma_linhas = aux;
    }
}

Regardless of what happens, at the end soma_linhas and aux will have the same value. What will be the value of aux . For a square of 3x3, it will be 0 in the first iteration, 1 in the second (+1) and 3 in the third (+2). However, that was not what he should do! There is no point in adding the values of i and disregarding the values of elem . You should check the values of elem .

However, even if you use aux += elem; , it will still be wrong, as this will end up adding all the values, not the values of each line separately.

What you have to do is to change this loop so that it adds up the values of each line and from the second line, compare with the value of the previous line.

Note that you are not storing the read values anywhere, the variable elem will only save the last value. Because of this, your loop to check the main diagonal will not work as you are only adding fixed values 0, 1 and 2 and completely ignoring the contents of the array.

Without storing the entire array, it is very difficult to verify that all rows and the main diagonal have the same values. But since you can not store values in vectors, you do the following:

  • Use a variable (let's call ok ) to indicate whether the sums of the lines and the main diagonal match. Initialize it with 1.

  • Read the first line, adding up all the items (let's call it a ). Store the first element in an auxiliary variable ( b ).

  • Use for to read the other lines, adding the elements of each line to another variable c . The main column element also adds the b variable. At the end of each line, check if a == c and change ok to 0 if it is not. Do not forget to return c to 0 before starting the next line.

  • When you finish the last line, check if a == b and change ok to 0 if it is not.

  • At the end, just check the variable ok .

Something like this:

#include <stdio.h>

int main() {

    int n;
    scanf("%d", &n);

    int elem, a = 0, b = 0, ok = 1;
    for (int i = 0; i < n; i++) {
        int c = 0;
        for (int j = 0; j < n; j++) {
            scanf("%d", &elem);
            if (i == j) b += elem;
            if (i == 0) a += elem;
            c += elem;
        }
        if (a != c) ok = 0;
    }
    if (a != b) ok = 0;

    if (ok) {
        printf("Quadrado misterioso com soma %d.", a);
    } else {
        printf("Não é um quadrado misterioso.");
    }
    return 0;
}

See working in ideone:

03.07.2018 / 07:15
3

You do not mention in the question anything about the sum of the columns, according to Wikipedia the definition of a Quadrado Mágico is:

  

Magic Square is a square table equal to the intersection of numbers   in which the sum of each column, each row and the two diagonals are   equal.

     

Here'satestedandcommentedsolutiontoseeifamysterioussquareismagicalornot,see:

#include<stdlib.h>#include<stdio.h>inteh_magico(int**quad,intn){inti=0,j=0;intx=0,y=0;intd1=0,d2=0;/*Somatoriodasdiagonais*/for(i=0;i<n;i++){d1+=quad[i][i];d2+=quad[n-i-1][i];}/*Verificasediagonaissaoiguais*/if(d1!=d2)return-1;for(i=0;i<n;i++){x=0;y=0;/*Somatoriolinhaecoluna*/for(j=0;j<n;j++){x+=quad[i][j];y+=quad[j][i];}/*Verificalinhaecoluna*/if(x!=d1||y!=d1)return-1;}/*Ehmagico!*/returnd1;}intmain(void){intlin,col,dim;int**quadrado_misterioso;/*Ledimensoes*/scanf("%d", &dim );

    /* Aloca memoria para n linhas */
    quadrado_misterioso = malloc( dim * sizeof(int*) );

    /* Para cada linha */
    for( lin = 0; lin < dim; lin++ )
    {
        /* Aloca memoria para n colunas da linha atual */
        quadrado_misterioso[lin] = malloc( dim * sizeof(int) );

        /* Para cada coluna da linha */
        for( col = 0; col < dim; col++ )
            scanf( "%d", &quadrado_misterioso[lin][col] );
    }

    /* Verifica se eh um quadrado magico */
    printf("%d\n", eh_magico( quadrado_misterioso, dim ) );

    /* Libera memoria ocupada pelo quadrado */
    for( lin = 0; lin < dim; lin++ )
        free(quadrado_misterioso[lin]);
    free(quadrado_misterioso);

    return 0;
}

Test (% with%):

3
4   9   2
3   5   7
8   1   6
15

Test (% with%):

4
2   16  13  3
11  5   8   10
7   9   12  6
14  4   1   15
34

Test (% with%):

5
1   23  16  4   21
15  14  7   18  11
24  17  13  9   2
20  8   19  12  6
5   3   10  22  25
65

Test (% with%):

3
1   2   3
4   5   6
7   8   9
-1

Test (% with%):

3
2   7   11
9   5   6
4   3   13
-1

See working at Ideone.com

    
03.07.2018 / 14:46