[英]Algorithm to determine whether a given number N can become hypotenuse of right triangle with all 3 integral sides
假設您給出了一個直角三角形的斜邊,那么如何確定給定的斜邊是否有兩個可能的整體較小的邊。
例如,你被賦予斜邊為5.然后你必須確定給定的直角三角形是否有較小的整數邊。答案是yes
因為我們可以將較小的邊用作3和4,因此得到3-4- 5直角三角形。
同樣,對於斜邊7,我們可以沒有這樣的直角三角形。
換句話說,我們必須找出給定數字N是否可以作為右三角形的斜邊,所有三邊都是整數。
我閱讀了關於畢達哥拉斯三重奏的整篇文章,但仍然沒有成功。我很困惑要檢查哪些條件。請幫忙。
你有一個原始的畢達哥拉斯三重奏:
(p^2 - q^2)^2 + (2 * p * q))^2 = (p^2 + q^2)^2 = N^2
假設p> = q。 然后我們有
N >= 2 * q^2 or q <= sqrt(N / 2)
假設N = 13.那么我們需要q <= sqrt(13/2)= 2.54
q = 2 => p ^ 2 = 13-4 = 9,這是一個正方形。
因此,您可以從1..sqrt(N / 2)獲得一個小數字'i'循環,並檢查N - (i ^ 2)是否為正方形。
對於原始畢達哥拉斯元組的成員,這將是O(sqrt(N)) 。
C / C ++中的示例代碼:
#include <stdio.h>
#include <math.h>
void CheckTuple(int n)
{
int k = sqrt(n/2.0);
for (int i = 1; i <= k; i++) {
int tmp = sqrt((double)(n - i * i));
if ((tmp * tmp) == (n - i * i)) {
printf("%d^2 + %d^2 = %d^2\n", (tmp*tmp - i*i), 2 * tmp * i, n);
return;
}
}
printf("%d is not part of a tuple\n", n);
return;
}
int main(int argc, char *argv[])
{
CheckTuple(5);
CheckTuple(6);
CheckTuple(13);
CheckTuple(10);
CheckTuple(25);
return 0;
}
輸出:
3^2 + 4^2 = 5^2
6 is not part of a tuple
5^2 + 12^2 = 13^2
8^2 + 6^2 = 10^2
7^2 + 24^2 = 25^2
int hypo = 5, i;
double other = 0;
for (i=1;i<hypo;i++)
{
other = Math.sqrt(hypo*hypo - i*i);
if (other == (int)other)
break;
}
if (i<hypo)
System.out.println("Yes - (" + (int)other + ", " + i +")" );
else
System.out.println("No");
上)
編輯:無需執行以下步驟,因為它將始終返回false。
//For each element in the array check whether twice its value equals N^2. If no match occurs then continue to the following.
。
Have two counters I1 and I2 -> Initialize I1 = 1 and I2 = N-1.
1. Check the sum I1^2 + I2^2;
2. If the sum is > N^2, decrement the right counter (I2).
3. If it is < N^2, increment the left counter (I1).
Keep doing the above 3 statements until one of the following happens.
-> If the sum matches N^2, then a right angled triangle can be formed.
-> If I2 <= I1, then it is not possible to form a triangle.
復雜性:O(N)
編輯:正如Dukeling指出的那樣,沒有必要存儲陣列。 你可以直接將I1和I2平方。
這個如何?
- > 2 for循環繼續到斜邊。 像這樣的東西:
public static boolean isAnIntegerTriangle(int hypotenuse) {
for (int i = 0; i < hypotenuse; i++) {
for (int j = 0; j < hypotenuse; j++) {
boolean b = ((hypotenuse * hypotenuse) == (i * i + j * j));
if (b)
return true;
}
}
return false;
}
測試:
public static void main(String[] args) {
System.out.println(isAnIntegerTriangle(5));
System.out.println(isAnIntegerTriangle(10));
System.out.println(isAnIntegerTriangle(7));
}
輸出:
true
true
false
這個問題一直是我在網上搜索最多的話題之一。 但解決方案很簡單。 得出答案,讓n可以是一個直角三角形的斜邊。 n ^ 2 = a ^ 2 + b ^ 2。 (n,a和b是整數)。 那么顯然對於任何整數k,k * n可以是斜邊的。 形式(4 * l + 1)的任何素數都可以是斜邊(l是整數)。 因此,將一個數字分成其主要因素。 如果至少有一個素因子是4 * l + 1的形式,那么顯然這個數字可以是斜邊的。 例如:5可以表示為4 * 1 + 1和5 ^ 2 = 3 ^ 2 + 4 ^ 2。 類似地,78 = 2 * 3 * 13和13可以表示為4 * 3 + 1。 並且13 ^ 2 = 5 ^ 2 + 12 ^ 2 => 78 ^ 2 = 30 ^ 2 + 72 ^ 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.