Ok, so I need to input a matrix of n elements and to replace each composite number with the closest prime number. I made functions for reading the matrix, showing the matrix, finding if a number is prime or not and finding the closest prime number to a number and they work.
Here is what I did and the problem is that the replacement does not work and I get the error: Process terminated with status -1073741510 (0 minute(s), 18 second(s))
#include <stdio.h>
#include <stdlib.h>
int n;
int readMatrix(int **matrix)
{
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
printf("matrix[%d][%d]=", i, j);
scanf("%d", &matrix[i][j]);
}
}
return matrix;
}
void showMatrix(int **matrix)
{
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int prime(int a)
{
int c = 0;
for (int i=1; i<a; i++) {
if (a % i == 0) {
c++;
}
}
if (c == 1) {
return 1;
} else return 0;
}
int nearPrime(int b)
{
int lp, bp, ok = 0, p;
lp = b - 1;
bp = b + 1;
while (ok != 1) {
if (prime(lp) == 1) {
ok = 1; break;
}
lp--;
}
ok = 0;
while (ok != 1) {
if (prime(bp) == 1) {
ok = 1; break;
}
bp++;
}
if ((b-lp) < (bp-b)) {
p = lp;
} else p = bp;
return p;
}
int main()
{
int **matrix, aux;
printf("n=");
scanf("%d", &n);
matrix = malloc(n*sizeof(int *));
if (matrix == NULL) exit(1);
for (int i=0; i<n; i++) {
matrix[i] = malloc(n*sizeof(int));
if (matrix[i] == NULL) exit(1);
}
readMatrix(matrix);
showMatrix(matrix);
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
if (prime(matrix[i][j]) == 0 && matrix[i][j] != 1) {
matrix[i][j] = nearPrime(matrix[i][j]);
}
}
}
showMatrix(matrix);
for (int i=0; i<n; i++) free(matrix[i]);
free(matrix);
return 0;
}
Can you tell me why it is not working?
UPDATE
I think I solved it. When checking if a matrix number is prime I also added the condition that it needs to be different than 1
because the program will return 0
when checking if 1
is prime number and it needs to return 1
since 1
is actually a prime number.
Thanks for all the tips!