📌  相关文章
📜  计算总和等于N的非负三元组

📅  最后修改于: 2021-04-23 05:35:14             🧑  作者: Mango

给定整数N。任务是找到非负整数的不同有序三元组(a,b,c)的数量,使a + b + c = N。
例子:

方法 :
首先,很容易看出,对于每个非负整数N ,方程( a + b = N)可以由(a + 1)个(N + 1)对不同的有序对来满足现在我们可以分配0N之间的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)