📜  建造给定等级N的纸牌屋所需的纸牌数量

📅  最后修改于: 2021-05-05 01:44:06             🧑  作者: Mango

给定数字N ,任务是找到制作N个等级的纸牌屋所需的纸牌数。

例子:

方法:

  1. 如果我们仔细观察,将形成如下所示的系列,其中第i个项目表示构成i个等级的金字塔所需的三角形卡片的数量:
  1. 上面的序列是一种差异序列的方法,其中AP中的差异为5、8、11、14……。等等。
  2. 因此,序列的第n个术语将是:
nth term = 2 + {5 + 8 + 11 +14 +.....(n-1) terms}
         = 2 + (n-1)*(2*5+(n-1-1)*3)/2
         = 2 + (n-1)*(10+(n-2)*3)/2
         = 2 + (n-1)*(10+3n-6)/2
         = 2 + (n-1)*(3n+4)/2
         = n*(3*n+1)/2;
  1. 因此,建造N个等级的纸牌屋所需的纸牌数为:

n*(3*n+1)/2

下面是上述方法的实现:

CPP
// C++ implementation of the above approach
 
#include 
using namespace std;
 
// Function to find number of cards needed
int noOfCards(int n)
{
    return n * (3 * n + 1) / 2;
}
 
// Driver Code
int main()
{
    int n = 3;
    cout << noOfCards(n) << ", ";
    return 0;
}


Java
// Java implementation of the above approach
import java.lang.*;
 
class GFG
{
    // Function to find number of cards needed
    public static int noOfCards(int n)
    {
        return n * (3 * n + 1) / 2;
    }
     
    // Driver Code
    public static void main(String args[])
    {
        int n = 3;
        System.out.print(noOfCards(n));
    }
}
 
// This code is contributed by shubhamsingh10


Python3
# Python3 implementation of the above approach
 
# Function to find number of cards needed
def noOfCards(n):
    return n * (3 * n + 1) // 2
 
# Driver Code
n = 3
print(noOfCards(n))
 
# This code is contributed by mohit kumar 29


C#
// C# implementation of the above approach
using System;
 
class GFG
{
    // Function to find number of cards needed
    public static int noOfCards(int n)
    {
        return n * (3 * n + 1) / 2;
    }
      
    // Driver Code
    public static void Main(String []args)
    {
        int n = 3;
        Console.Write(noOfCards(n));
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
15

时间复杂度: O(1)