![](/img/trans.png)
[英]consider x^i+y^i=z^i x<=y<=z<=m and 2<=i<=n (m and n are inputs) m can vary from 5 to 100 n can vary from 2 to 100
[英]Error in C program to find integer triplets (x,y,z) such that n^x + n^y = n^z for given range of n
我想使C程序與DEV-C ++ 4.9.9.2兼容,以查找整數三元組(x,y,z)
,以便對於任何整數n,方程n^x + n^y = n^z
成立,其中n
是任何n
[a,b]
范圍內的整數。 c程序將僅a
和b
的輸入,並找到此類可能的三元組。
我編寫的代碼無法正常工作。 有什么錯誤嗎?
for (n = a ; n <= b ; n++) {
for (x = a ; x < b ; x++) {
for (y = a ; y < b ; y++) {
for (z = a ; z = b ; z++) {
c = pow(n, x);
d = pow(n, y);
e = pow(n, z);
f = c + d;
if (e = f) {
printf("(%d , %d , %d) : %d", x,y,z,n);
}
}
}
}
}
我是C語言的新手。
嘗試改變
if (e=f)
進入
if (e==f)
第一個執行分配,第二個測試是否相等。
(請注意,如果測試的數字大於數據類型,您也可能會溢出。)
如果y == x,則:
n^x + n^x = n^z
2n^x = n^z
=> n == 0 or n == 2
現在,假設y> x且n!= 0。
n^x + n^y = n^z
n^x ( 1 + n^(y-x)) = n^z
=> 1+n^(y-x) = n^(z-x)
=> 1 = 0 ( modulo n)
=> impossible unless n==0 (in which case any x,y works) or n==1 (which does not work)
因此,如果n == 0,則此方程式具有任何x,y的解。 否則,唯一的解決方案是n == 2,x == y和z = x + 1。
更改
if (e = f)
至
if (e == f)
第一個將f
分配給e
,為此類錯誤啟用編譯器警告。 第二個將LHS等同於RHS。
其次,假設您的程序是蠻力的,即針對x
, y
和z
所有值循環,則可能需要更改以下語句:
for (z = a ; z = b ; z++)
至
for (z = a ; z < b ; z++)
您的實現是O(n ^ 4),實際上可以在O(n ^ 3)中完成。
for (n = a ; n <= b ; n++) {
for (x = a ; x < b ; x++) {
for (y = a ; y < b ; y++) {
{
c = pow(n, x);
d = pow(n, y);
f = c + d;
e = pow(f,1.0/n);
if (e >= a && e < b) {
z = e;
printf("(%d , %d , %d) : %d", x,y,z,n);
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.