Find the sum of elements of the Matrix generated by the given rules
Given three integers A, B, and R, the task is to find the sum of all the elements of the matrix generated by the given rules:
- The first row will contain a single element which is A and the rest of the elements will be 0.
- The next row will contain two elements all of which are (A + B) and the rest are 0s.
- Third row will contain (A + B + B) three times and the rest are 0s and so on.
- The matrix will contain only R rows.
For example, if A = 5, B = 3 and R = 3 then the matrix will be:
5 0 0
8 8 0
11 11 11
Input: A = 5, B = 3, R = 3
5 + 8 + 8 + 11 + 11 + 11 = 54
Input: A = 7, B = 56, R = 1
Approach: Initialize sum = 0 and for every 1 ≤ i ≤ R update sum = sum + (i * A). After every iteration update A = A + B. Print the final sum in the end.
Below is the implementation of the above approach:
Time Complexity: O(R)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.