给定数字N ,任务是找到制作N个等级的纸牌屋所需的纸牌数。
例子:
Input: N = 3
Output: 15
From the above image, it is clear that for the House of Cards for 3 levels 15 cards are needed
Input: N = 2
Output: 7
方法:
- 如果我们仔细观察,将形成如下所示的系列,其中第i个项目表示构成i个等级的金字塔所需的三角形卡片的数量:
2, 7, 15, 26, 40, 57, 77, 100, 126, 155………and so on.
- 上面的序列是一种差异序列的方法,其中AP中的差异为5、8、11、14……。等等。
- 因此,序列的第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;
- 因此,建造N个等级的纸牌屋所需的纸牌数为:
下面是上述方法的实现:
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)