Find the maximum product of Pythagorean triplet such than a^2+b^2=c^2 and a + b + c=n.
Example 1:
Input: n=12 Output: 60 //3 4 5
Approach:
Java
public class SpecialPythagoreanTriplet {
public static void main(String[] args) {
int n = 12;
System.out.println(maxProduct(n));
}
//function to find the maximum
//product of pythagorean
//triplet such that a+b+c=n and a^2+b^2=c^
static int maxProduct(int n) {
int ans = -1;
int b, c;
for (int a = 1; a <= n / 3; a++) {
// solve for b and c
b = (n * n - 2 * n * a) / (2 * n - 2 * a);
c = n - a - b;
if (c * c == (a * a + b * b)) {
int prod = a * b * c;
if (prod > ans)
ans = prod;
}
}
return ans;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to find the maximum
//product of pythagorean
//triplet such that a+b+c=n and a^2+b^2=c^
int maxProduct(int n)
{
int ans=-1;
int b,c;
for(int a=1;a<=n/3;a++)
{
//solve for b and c
b=(n*n-2*n*a)/(2*n-2*a);
c=n-a-b;
if(c*c==(a*a+b*b))
{
int prod=a*b*c;
if(prod>ans)
ans=prod;
}
}
return ans;
}
int main()
{
int n=12;
cout<<maxProduct(n);
return 0;
}
No comments:
Post a Comment