📌  相关文章
📜  查找由给定规则生成的矩阵元素的总和

📅  最后修改于: 2021-04-27 19:06:46             🧑  作者: Mango

给定三个整数ABR ,任务是找到由给定规则生成的矩阵的所有元素的总和:

  1. 第一行将包含一个元素A ,其余元素将为0
  2. 下一行将包含两个元素,所有元素均为(A + B) ,其余均为0s
  3. 第三行将包含(A + B + B) 3次,其余为0s
  4. …..
  5. 矩阵将仅包含R行。

例如,如果A = 5B = 3R = 3,则矩阵将为:
5 0 0
8 8 0
11 11 11
例子:

方法:初始化总和= 0,并且每1≤i≤R更新总和= sum +(i * A) 。每次迭代后,更新A = A + B。最后打印最终金额。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the required sum
int sum(int A, int B, int R)
{
 
    // To store the sum
    int sum = 0;
 
    // For every row
    for (int i = 1; i <= R; i++) {
 
        // Update the sum as A appears i number
        // of times in the current row
        sum = sum + (i * A);
 
        // Update A for the next row
        A = A + B;
    }
 
    // Return the sum
    return sum;
}
 
// Driver code
int main()
{
 
    int A = 5, B = 3, R = 3;
    cout << sum(A, B, R);
 
    return 0;
}


Java
// JAVA implementation of the approach
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG
{
 
// Function to return the required sum
static int sum(int A, int B, int R)
{
 
    // To store the sum
    int sum = 0;
 
    // For every row
    for (int i = 1; i <= R; i++)
    {
 
        // Update the sum as A appears i number
        // of times in the current row
        sum = sum + (i * A);
 
        // Update A for the next row
        A = A + B;
    }
 
    // Return the sum
    return sum;
}
 
// Driver code
public static void main (String[] args)
              throws java.lang.Exception
{
    int A = 5, B = 3, R = 3;
     
    System.out.print(sum(A, B, R));
}
}
 
// This code is contributed by nidhiva


Python3
# Python3 implementation of the approach
 
# Function to return the required ssum
def Sum(A, B, R):
 
    # To store the ssum
    ssum = 0
 
    # For every row
    for i in range(1, R + 1):
 
        # Update the ssum as A appears i number
        # of times in the current row
        ssum = ssum + (i * A)
 
        # Update A for the next row
        A = A + B
 
    # Return the ssum
    return ssum
 
# Driver code
A, B, R = 5, 3, 3
print(Sum(A, B, R))
 
# This code is contributed by Mohit Kumar


C#
// C# implementation of the approach
using System;
 
class GFG
{
 
// Function to return the required sum
static int sum(int A, int B, int R)
{
 
    // To store the sum
    int sum = 0;
 
    // For every row
    for (int i = 1; i <= R; i++)
    {
 
        // Update the sum as A appears i number
        // of times in the current row
        sum = sum + (i * A);
 
        // Update A for the next row
        A = A + B;
    }
 
    // Return the sum
    return sum;
}
 
// Driver code
public static void Main ()
{
    int A = 5, B = 3, R = 3;
     
    Console.Write(sum(A, B, R));
}
}
 
// This code is contributed by anuj_67..


输出:
54

时间复杂度: O(R)

辅助空间: O(1)