A Pythagorean triple consists of three positive integers a,b, and,c such that . Such a triple is commonly written as (a,b,c). This term comes from the Pythagorean theorem, which says that a Pythagorean Triple will be the lengths of the sides of a right-angled triangle.
You have been given an integer that represents the length of one of the catheti of a right-angle triangle.
You need to find the lengths of the remaining sides. There may be multiple possible answers; anyone will be accepted.
Hints:
- Every odd number can be represented as .
- If and are integers and , then .
Example:
Input: a = 5
Output: 5 12 13
Approach
Java
import java.util.Arrays;public class PythagoreanTriplet {public static void main(String[] args) {long a = 5;long[] triple = pythagoreanTriple(a);System.out.println(Arrays.toString(triple));}static long[] pythagoreanTriple(long a) {long b, c;if (a % 2 != 0) {b = (a * a - 1) / 2;c = b + 1;} else {b = (a / 2) * (a / 2) - 1;c = b + 2;}long[] res = new long[3];res[0] = a;res[1] = b;res[2] = c;return res;}}
C++
#include <bits/stdc++.h>using namespace std;vector<long long int> pythagoreanTriple(long long int a){long long int b, c;if (a % 2 != 0){b = (a * a - 1) / 2;c = b + 1;}else{b = (a / 2) * (a / 2) - 1;c = b + 2;}vector<long long int> res;res.push_back(a);res.push_back(b);res.push_back(c);return res;}int main(){long long int a = 5;vector<long long int> triple = pythagoreanTriple(a);for (int i = 0; i < triple.size(); i++){cout << triple[i];if (i != triple.size() - 1){cout << " ";}}return 0;}
No comments:
Post a Comment