[英]How to find out whether two numbers are powers of the same number and those powers
所以假设你得到了数字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
你可以利用一个简单的事实,即同数的幂可以被彼此整除。 和产品本身是同根的力量。 这意味着我们可以有一个简单的递归算法,如下所示:
-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
对于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,它是 a 的第 x x'th root of a
x,并返回y'th root of b
的相应 y。 通过执行a^(1/x)
或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.
}
请注意,此算法可能会返回最高的公共根,而不是最低的。
我很高兴为您找到优化的解决方案,希望对您有所帮助:)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.