所以說你得到了數字27和81。一個程式會告訴你 81 的 4 次根是 3,27 的三次根是 3。(兩者的根都是 3)。
x = 16;
y = 4;
foo = same_root(16, 4); // foo = 2
root1 = find_root(16, 2); // root1 = 4
root2 = find_root(4, 2); // root2 = 2
uj5u.com熱心網友回復:
你可以利用一個簡單的事實,即同數的冪可以被彼此整除。和產品本身是同根的力量。這意味著我們可以有一個簡單的遞回演算法,如下所示:
- 檢查較小的數字是否除以較大的數字。
- 如果不是 - 回傳 false (
-1在下面的代碼中) - 如果是,遞回地重復較小的數字和產品
我們的停止條件應該是兩個數字相等,但兩者都不相等,1因為1不能是公共根。
這是實作這個想法的 C 代碼(對于正數):
#include <stdio.h>
#define TEST(x, y) printf("%d, %d => %d\n", (x), (y), common_root((x),(y)))
int common_root(int a, int b)
{
int temp;
if (a == 1 || b == 1)
return -1;
if (a == b) {
return a;
}
if (a > b) {
// Swap to make sure a < b
temp = a;
a = b;
b = temp;
}
if ( (b % a) == 0) // Check if `b` divisible by `a`
return common_root(a, b/a);
else
return -1;
}
int main(void) {
TEST(1,2);
TEST(2,3);
TEST(6,10);
TEST(4, 16);
TEST(12, 24);
TEST(27, 81);
return 0;
}
輸出:
1, 2 => -1
2, 3 => -1
6, 10 => -1
4, 16 => 4
12, 24 => -1
27, 81 => 3
演示
uj5u.com熱心網友回復:
對于CommonRoot(a,b),
你說x'th root of a = y'th root of b,
這與 a^(1/x) = b^(1/y)
所以隔離 y :
//log_x is log base x
log_b(a^(1/x)) = 1/y
(1/x)log_b(a) = 1/y
x/log_b(a) = y
//Or
x/(log(a)/log(b)) = y
該函式將接收條目 x,即 x 的 x,x'th root of a并回傳對應的 y y'th root of b。通過執行a^(1/x)or b^(1/y),您可以找到共同根。
因此,您可以遍歷 x 的值,等待獲得整數 y,如果這樣做b^(1/y),您將獲得一個公共根。值得一提的是,此方法可幫助您找到多個公共根和非整數公共根。
所以這是一個偽代碼示例:
CommonRoot(float a, float b){
For(int x = 0; x < max(a,b); x ){ // max(a,b) is just to set a threshold of search,
//I haven't actually tested this, so I don't know what would be a good threshold
float y = x/(log(a)/log(b)); // gather a y for an x
If ( fPart(y) == 0){ // test if y is an integer
If( fPart(b^(1/y)) == 0){ // the answer might lead to a non-integer common root (such as 1.4 beeing a common root of 1.4^2 and 1.4^5)
return b^(1/y); //return the common root
}
}
}
return -1; //if it hasn't found anything, return -1 or error.
}
請注意,此演算法可能會回傳最高的公共根,而不是最低的。
我很高興為您找到優化的解決方案,希望對您有所幫助:)。
uj5u.com熱心網友回復:
使用素數分解(此處概述),您可以制作一個除數串列,然后簡單地檢查兩個串列中的哪些值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/483280.html
下一篇:不使用回圈輸入任何數學表
