给定整数N ,任务是找到将N分解为可以一起形成三角形的有序三胞胎的方法数量。
例子:
Input: N = 15
Output: Total number of triangles possible are 28
Input: N = 9
Output: Total number of triangles possible is 10
方法:为了解决该问题,需要进行以下观察:
If N is split into 3 integers a, b and c, then the following conditions need to be satisfied for a, b and c to form a triangle:
因此,使用嵌套循环在[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 traingle
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));
}
}
输出:
28
时间复杂度: O(N 2 )
辅助空间: O(N)