Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Last active June 13, 2025 16:33
Show Gist options
  • Save thinkphp/cbdbf35fd7376e629a05ec833140f099 to your computer and use it in GitHub Desktop.
Save thinkphp/cbdbf35fd7376e629a05ec833140f099 to your computer and use it in GitHub Desktop.
matrix_div_k.cpp
#include <iostream>
#include <vector>
using namespace std;
int sumDivisibleRecursive(vector<vector<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 sumDivisibleRecursiveAlt(vector<vector<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(vector<vector<int>> &matrix, int k) {
int n = matrix.size();
return sumDivisibleRecursiveAlt(matrix, k, 0, n);
}
int sumDivByRecursive(vector<vector<int>> &matrix, int k) {
int n = matrix.size();
return sumDivisibleRecursive(matrix, k, 0, 0, n);//linie 0 , coloana 0
}
vector<vector<int>> readMatrix() {
int n;
cout<<"Enter the size of square matrix (n x n): ";
cin>>n;
vector<vector<int>> matrix(n, vector<int>(n));
for(int i = 0; i < n; ++i) {
cout<<"Row "<< i + 1<< ": ";
for(int j = 0; j < n; ++j) {
cin>>matrix[i][j];//(0,0) (0,1) (0,2)
}
}
return matrix;
}
void displayMatrix(vector<vector<int>> matrix) {
int n = matrix.size();
cout<<"\nMatrix: \n";
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
cout<<matrix[i][j]<<"\t";
}
cout<<"\n";
}
}
//5! = 5 * 4 * 3 * 2 * 1
// 5
int fact(int n) {
if(n == 1) return 1;
else return n * fact(n - 1);
//5 * fact(4)
}
/*
1
2
3 |
4 / \
5 ||
*/
int main(int argc, char const *argv[]) {
//cout<<fact(5);//primul apel
vector<vector<int>> matrix = readMatrix();
int k;
cout<<"k = ";
cin>>k;
displayMatrix(matrix);
int sumRecursive= sumDivByRecursive(matrix, k);
int sumRecursive2= sumDivByRecursiveAlt(matrix, k);
cout<<"Sum = "<<sumRecursive<<endl;
cout<<"Sum = "<<sumRecursive2;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment