给定整数N。任务是找到非负整数的不同有序三元组(a,b,c)的数量,以使a + b + c = N。
例子:
Input : N = 2
Output : 6
Triplets are : (0, 0, 2), (1, 0, 1), (0, 1, 1), (2, 0, 0), (0, 2, 0), (1, 1, 0)
Input : N = 50
Output : 1326
方法 :
首先,很容易看出,对于每个非负整数N ,方程( a + b = N)可以由(a + 1)个(N + 1)对不同的有序对来满足。现在我们可以分配0到N之间的c值,然后可以找到a + b的有序对。它将形成一系列N + 1个自然数,其总和将得出三元组的数量。
下面是上述方法的实现:
C++
// CPP program to find triplets count
#include
using namespace std;
// Function to find triplets count
int triplets(int N)
{
// Sum of first n+1 natural numbers
return ((N + 1) * (N + 2)) / 2;
}
// Driver code
int main()
{
int N = 50;
// Function call
cout << triplets(N);
return 0;
}
Java
// Java program to find triplets count
class GFG
{
// Function to find triplets count
static int triplets(int N)
{
// Sum of first n+1 natural numbers
return ((N + 1) * (N + 2)) / 2;
}
// Driver code
public static void main(String[] args)
{
int N = 50;
System.out.println(triplets(N));
}
}
// This code is contributed
// by PrinciRaj1992
Python3
# Python3 program to find triplets count
# Function to find triplets count
def triplets(N):
# Sum of first n+1 natural numbers
return ((N + 1) * (N + 2)) // 2;
# Driver code
N = 50;
# Function call
print(triplets(N))
# This code is contributed by nidhi
C#
// C# program to find triplets count
using System;
class GFG
{
// Function to find triplets count
static int triplets(int N)
{
// Sum of first n+1 natural numbers
return ((N + 1) * (N + 2)) / 2;
}
// Driver code
public static void Main()
{
int N = 50;
Console.WriteLine(triplets(N));
}
}
// This code is contributed
// by anuj_67..
Javascript
输出:
1326
时间复杂度: O(1)