毕达哥拉斯三胞胎是一组自然数,使得a
给定数字N,找到总和为给定N的勾股三重态或返回-1。
例子:
Input: 12
Output: 3 4 5
Explanation:
As 32 + 42 = 52
Input: 82
Output: -1
方法:我们的想法是找到一个条件b和c的值和一个迭代从1到N为了找到b和c的一个方面,我们要做以下值:
我们有两个方程
[Tex] a + b + c = N [/ Tex]
我们将根据a和b来找到c的值,然后将该值放在等式1中以求解b。
根据等式2,
现在,将该值放在等式1中。
求解完上述方程式后,我们将得到,
[Tex] c = N – b – a [/ Tex]
现在,将a从1迭代到N,然后分别计算b和c的值。然后,检查是否
C++
// C++ program to find the Pythagorean
// Triplet with given sum
#include
using namespace std;
// Function to calculate the
// Pythagorean triplet in O(n)
void PythagoreanTriplet(int n)
{
int flag = 0;
// Iterate a from 1 to N-1.
for (int a = 1; a < n; a++)
{
// Calculate value of b
int b = (n * n - 2 * n * a)
/ (2 * n - 2 * a);
// The value of c = n - a - b
int c = n - a - b;
if (a * a + b * b == c * c
&& b > 0 && c > 0)
{
cout << a << " " << b << " " << c;
flag = 1;
break;
}
}
if (flag == 0) {
cout << "-1";
}
return;
}
// Driver Code
int main()
{
int N = 12;
// Function call
PythagoreanTriplet(N);
return 0;
}
Java
// Java program to find the Pythagorean
// Triplet with given sum
class GFG {
// Function to calculate the
// Pythagorean triplet in O(n)
static void PythagoreanTriplet(int n)
{
int flag = 0;
// Iterate a from 1 to N-1.
for (int a = 1; a < n; a++)
{
// Calculate value of b
int b = (n * n - 2 * n * a)
/ (2 * n - 2 * a);
// The value of c = n - a - b
int c = n - a - b;
if (a * a + b * b == c * c
&& b > 0 && c > 0)
{
System.out
.print(a + " " + b + " " + c);
flag = 1;
break;
}
}
if (flag == 0)
{
System.out.print("-1");
}
return;
}
// Driver Code
public static void main(String[] args)
{
int N = 12;
// Function call
PythagoreanTriplet(N);
}
}
// This code contributed by sapnasingh4991
Python3
# Python3 program to find the Pythagorean
# Triplet with a given sum
# Function to calculate the
# Pythagorean triplet in O(n)
def PythagoreanTriplet(n):
flag = 0
# Iterate a from 1 to N-1.
for a in range(1, n, 1):
# Calculate value of b
b = (n * n - 2 * n * a) // (2 * n - 2 * a)
# The value of c = n - a - b
c = n - a - b
if (a * a + b * b == c * c
and b > 0 and c > 0):
print(a, b, c)
flag = 1
break
if(flag == 0):
print("-1")
return
# Driver code
if __name__ == '__main__':
N = 12
# Function call
PythagoreanTriplet(N)
# This code is contributed by Bhupendra_Singh
C#
// C# program to find the Pythagorean
// Triplet with given sum
using System;
class GFG {
// Function to calculate the
// Pythagorean triplet in O(n)
static void PythagoreanTriplet(int n)
{
int flag = 0;
// Iterate a from 1 to N-1.
for (int a = 1; a < n; a++)
{
// Calculate value of b
int b = (n * n - 2 * n * a)
/ (2 * n - 2 * a);
// The value of c = n - a - b
int c = n - a - b;
if (a * a + b * b == c * c
&& b > 0 && c > 0)
{
Console.Write(a + " " + b + " " + c);
flag = 1;
break;
}
}
if (flag == 0) {
Console.Write("-1");
}
return;
}
// Driver code
public static void Main(String[] args)
{
int N = 12;
// Function call
PythagoreanTriplet(N);
}
}
// This code is contributed by shivanisinghss2110
Javascript
输出
3 4 5
时间复杂度: O(N)