Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created June 13, 2025 17:03
Show Gist options
  • Save thinkphp/37f3ca576e9cec0f383bef31fd1d1800 to your computer and use it in GitHub Desktop.
Save thinkphp/37f3ca576e9cec0f383bef31fd1d1800 to your computer and use it in GitHub Desktop.
matrix_div_k.c
#include <stdio.h>
#include <malloc.h>
int sumDivisibleRecursiveAlt(int **matrix, int k, int index, int n) {
if(index >= n * n) {
return 0;
}
int row = index / n;
int col = index % n;
int currentSum = 0;
if(matrix[row][col] % k == 0) currentSum = matrix[row][col];
return currentSum + sumDivisibleRecursiveAlt(matrix, k, index + 1, n);
}
//wrapper for recursion alternative
int sumDivByRecursiveAlt(int **matrix, int k, int n) {
return sumDivisibleRecursiveAlt(matrix, k, 0, n);
}
int sumDivisibleRecursive(int **matrix, int k, int row, int col, int n) {
if(row >= n) {
return 0;
}
if(col >= n) {
return sumDivisibleRecursive(matrix, k, row + 1, 0, n);
}
int currentSum = 0;
if(matrix[row][col] % k == 0) currentSum = matrix[row][col];
return currentSum + sumDivisibleRecursive(matrix, k, row, col+1, n);//0, 1, 3
}
int **readMatrix(int *size) {
int n;
printf("Enter the size of square matrix (n x n): ");
scanf("%d", &n);
*size = n;
int **matrix = (int**)malloc(n * sizeof(int*));
for(int i = 0; i < n; i++) {
matrix[ i ] = (int*)malloc(n * sizeof(int));
}
printf("Enter the matrix elements: \n");
for(int i = 0; i < n; ++i) {
printf("Row %d: ", i + 1);
for(int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
}
}
return matrix;
}
void displayMatrix(int **matrix, int n) {
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int n;
int k;
int **matrix = readMatrix(&n);
displayMatrix(matrix, n);
printf("k = ");
scanf("%d",&k);
printf("\nResults: \n");
printf("Sum using Recursive approach: \n");
int sumRecursive = sumDivByRecursiveAlt(matrix, k, n);
printf("sum = %d", sumRecursive);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment