📌  相关文章
📜  将 N 分成形成三角形的三元组的方法数

📅  最后修改于: 2021-10-26 02:28:25             🧑  作者: Mango

给定一个整数N ,任务是找到将N分成可以一起形成三角形的有序三元组的方法数。

例子:

处理方法:为了解决问题,需要进行以下观察:

因此,使用嵌套循环迭代范围[1, N]以生成三元组,并为每个三元组检查它是否形成三角形。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to return the
// required number of ways
int Numberofways(int n)
{
    int count = 0;
 
    for (int a = 1; a < n; a++) {
 
        for (int b = 1; b < n; b++) {
 
            int c = n - (a + b);
 
            // Check if a, b and c can
            // form a triangle
            if (a + b > c && a + c > b
                && b + c > a) {
                count++;
            }
        }
    }
 
    // Return number of ways
    return count;
}
 
// Driver Code
int main()
{
    int n = 15;
 
    cout << Numberofways(n) << endl;
 
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.io.*;
 
class GFG {
 
    // Function to return the
    // required number of ways
    static int Numberofways(int n)
    {
        int count = 0;
 
        for (int a = 1; a < n; a++) {
 
            for (int b = 0; b < n; b++) {
 
                int c = n - (a + b);
 
                // Check if a, b, c can
                // form a triangle
                if (a + b > c && a + c > b
                    && b + c > a) {
                    count++;
                }
            }
        }
 
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int n = 15;
 
        System.out.println(Numberofways(n));
    }
}


Python3
# Python Program to implement
# the above approach
 
# Function to return the
# required number of ways
def Numberofways(n):
    count = 0
    for a in range(1, n):
        for b in range(1, n):
 
            c = n - (a + b)
 
            # Check if a, b, c can form a triangle
            if(a < b + c and b < a + c and c < a + b):
                count += 1
 
    return count
 
 
# Driver code
n = 15
print(Numberofways(n))


C#
// C# Program to implement
// the above approach
 
using System;
 
class GFG {
 
    // Function to return the
    // required number of ways
    static int Numberofways(int n)
    {
        int count = 0;
        for (int a = 1; a < n; a++) {
            for (int b = 1; b < n; b++) {
                int c = n - (a + b);
 
                // Check if a, b, c can form
                // a triangle or not
                if (a + b > c && a + c > b
                    && b + c > a) {
                    count++;
                }
            }
        }
 
        // Return number of ways
        return count;
    }
 
    // Driver Code
    static public void Main()
    {
        int n = 15;
 
        Console.WriteLine(Numberofways(n));
    }
}


Javascript


输出:
28

时间复杂度: O(N 2 )
辅助空间: O(N)