Find the sum of elements of the Matrix generated by the given rules
Last Updated :
28 May, 2022
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
Examples:
Input: A = 5, B = 3, R = 3
Output: 54
5 + 8 + 8 + 11 + 11 + 11 = 54
Input: A = 7, B = 56, R = 1
Output: 7
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:
C++
#include <iostream>
using namespace std;
int sum( int A, int B, int R)
{
int sum = 0;
for ( int i = 1; i <= R; i++) {
sum = sum + (i * A);
A = A + B;
}
return sum;
}
int main()
{
int A = 5, B = 3, R = 3;
cout << sum(A, B, R);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static int sum( int A, int B, int R)
{
int sum = 0 ;
for ( int i = 1 ; i <= R; i++)
{
sum = sum + (i * A);
A = A + B;
}
return sum;
}
public static void main (String[] args)
throws java.lang.Exception
{
int A = 5 , B = 3 , R = 3 ;
System.out.print(sum(A, B, R));
}
}
|
Python3
def Sum (A, B, R):
ssum = 0
for i in range ( 1 , R + 1 ):
sum = sum + (i * A)
A = A + B
return sum
A, B, R = 5 , 3 , 3
print ( Sum (A, B, R))
|
C#
using System;
class GFG
{
static int sum( int A, int B, int R)
{
int sum = 0;
for ( int i = 1; i <= R; i++)
{
sum = sum + (i * A);
A = A + B;
}
return sum;
}
public static void Main ()
{
int A = 5, B = 3, R = 3;
Console.Write(sum(A, B, R));
}
}
|
Javascript
<script>
function sum( A, B, R)
{
let sum = 0;
for (let i = 1; i <= R; i++)
{
sum = sum + (i * A);
A = A + B;
}
return sum;
}
let A = 5, B = 3, R = 3;
document.write(sum(A, B, R));
</script>
|
Time Complexity: O(R), since there runs a loop for once from 1 to R.
Auxiliary Space: O(1), since no extra space has been taken.
Share your thoughts in the comments
Please Login to comment...