Problem Statement:
Consider A is a square matrix with size N. Write a program to replace every element A[i][j] of the matrix with a number that is nearest to or equal to A[i][ j] divisible by 5.
Read the input from STDIN and write the output to STDOUT. You should not write arbitrary strings while reading the input and while printing as these contribute to the standard output.
Constraints:
Input Format:
Output Format:
Sample Input 1:
2
1 8
3 6
Sample Output 1:
0 10
5 5
Explanation 1:
From the Sample Input 1, we have:
2
1 8
3 6
Topics Involved / Prerequisites
Overview
Approach
1. The Mathematics of Rounding
Using modulo arithmetic avoids floating-point inaccuracies. We calculate the quotient q = x / 5 and remainder r = x % 5. For positive numbers, if r > 2, the nearest multiple is (q + 1) * 5. For negative numbers, if r < -2, the nearest multiple is (q - 1) * 5. Otherwise, the nearest multiple is simply q * 5.
2. On-the-Fly Processing
Since we only need to print the transformed matrix, we do not need to store the entire N \times N matrix in memory. We can read each element, instantly compute its nearest multiple of 5, and print it directly to the standard output, ensuring the spatial complexity remains absolute minimal.
C++ code implementation -:
#include <iostream>
using namespace std;
int main() {
// Optimize standard I/O operations for performance
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
// Read the size of the matrix. If no input, exit safely.
if (!(cin >> n)) return 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int x;
cin >> x;
int q = x / 5;
int r = x % 5;
int nearest;
// Handle positive rounding up
if (r > 2) {
nearest = (q + 1) * 5;
}
// Handle negative rounding down
else if (r < -2) {
nearest = (q - 1) * 5;
}
// Round to the current quotient
else {
nearest = q * 5;
}
// Print the element followed by a single whitespace
cout << nearest << " ";
}
// Print a newline at the end of each row
cout << "\n";
}
return 0;
}Time and space Complexity