Answer the question
In order to leave comments, you need to log in
Why does the compiler swear at a boolean function?
Good evening!
Here's the actual task:
The point is to specify a point with coordinates i, j in a huge array, then, relative to this point in the selected area, find and put the sum of all prime numbers from this area into the SUM variable.
Here is the actual code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
bool prime(int n){
int i;
for(i = 2;i <= sqrt(n); i++)
if(n % i == 0)
return false;
return true;
}
int obrabotka (int i, int j, int N, int M, int A[15][15]){
int a, S, k, l;
if(prime(A[i][j]) == true){
S += A[i][j];
}
a = 0;
k = i;
l = j;
while(a <= 3){
k--;
l--;
if(prime(A[k][l]) == true){
S += A[k][l];
}
a++;
}
a = 0;
k = i - 1;
l = j + 1;
while(a <= 1){
k--;
l++;
if(prime(A[k][l]) == true){
S += A[k][l];
}
a++;
}
a = 0;
k = i + 1;
l = j - 3;
while(a < 6){
l++;
if(prime(A[k][l]) == true){
S += A[k][l];
}
a++;
}
return S;
}
void main ()
{
int N, M, i, j, A[15][15], S;
printf ("vvedite N i M\n");
scanf ("%d % d", &N, &M);
printf ("vvedite matrizu\n");
for (i = 1; i <= N; i++)
for (j = 1; j<=M; j++)
scanf ("%d", &A[i][j]);
printf ("vvedite i i j\n");
scanf ("%d %d", &i, &j);
S=obrabotka(i,j,N,M,A);
printf("--------------");
printf ("| № | i | j | result|");
printf("--------------");
printf ("| 1 |%3d |%3d |%6d |", i, j, S);
printf("--------------");
getch();
}
Answer the question
In order to leave comments, you need to log in
Well, as if the identifier true is undeclared,
do
either
#define true 1
#define false 0
I would like to know what is the problem
Your code may overflow arrays.
In your code, the dimensions of the selected area are hard-coded, but, as far as I understand from the condition of the assignment, the area expands or contracts with a different matrix size.
In addition, it was meant to find the required sum for each pair (i, j), and not just for the given one.
The algorithm can also be optimized if you first go through the entire array and set the composite (not prime) numbers to zero. Otherwise, you will end up with a lot of prime() calls.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question