在 Java 中仅使用加法进行指数运算
Doing exponential operation using only addition in Java
我在制作这个程序时遇到了问题。不使用*, ^, Math.pow
,是否可以通过获取指数值来编写程序?示例我的底数为 2,指数为 3。
Q1. what operation should I used to help the addition to come up with the correct result?
Q2. addition is enough?
为什么你不能使用语言的那些功能?
不管怎样:
public int pow (final int base, final int exponent) {
int result = base;
for (int i = 1; i < exponent; i++)
for (int j = 0; j < base; j++)
result += base;
return result;
}
这显然只适用于整数(或者实际上是长整数),如果你有一个浮动值作为指数我不认为你可以避免 ^ 或 Math.pow
请注意,我还没有对此进行测试,但应该按照这个思路工作,我可能在某处搞砸了。
你还应该注意到 x^0=1,所以在那里添加一个额外的检查。这仅适用于有符号整数,因为该算法不适用于负数
是的,可以只用加法求幂。请记住,乘法是多次重复加法,求幂是多次重复乘法。
例如,您可以编写以下函数来对一个数求幂:
double exp(long base, long exponent) {
//when the exponent is zero
if (exponent == 0) return 1.0;
long result = base;
long exponent_abs = Math.abs(exponent);
//repeating multiplication many times to achieve exponentiation
for (int i = 2 ; i <= exponent_abs ; ++i) {
result = multiply(result, base);
}
//if the exponent is positive, return result you found.
if (exponent > 0) return result;
//if it is negative, return a fraction.
return 1/((double)result);
}
//repeating addition many times to achieve multiplication.
long multiply(long number1, long number2){
long result = number1;
for (int i = 1; i < number2; ++i){
result += number1;
}
return result;
}
注意函数returns是double值,因为如果你的指数是负数,结果不能用整数类型表示。
我在制作这个程序时遇到了问题。不使用*, ^, Math.pow
,是否可以通过获取指数值来编写程序?示例我的底数为 2,指数为 3。
Q1. what operation should I used to help the addition to come up with the correct result?
Q2. addition is enough?
为什么你不能使用语言的那些功能? 不管怎样:
public int pow (final int base, final int exponent) {
int result = base;
for (int i = 1; i < exponent; i++)
for (int j = 0; j < base; j++)
result += base;
return result;
}
这显然只适用于整数(或者实际上是长整数),如果你有一个浮动值作为指数我不认为你可以避免 ^ 或 Math.pow
请注意,我还没有对此进行测试,但应该按照这个思路工作,我可能在某处搞砸了。
你还应该注意到 x^0=1,所以在那里添加一个额外的检查。这仅适用于有符号整数,因为该算法不适用于负数
是的,可以只用加法求幂。请记住,乘法是多次重复加法,求幂是多次重复乘法。
例如,您可以编写以下函数来对一个数求幂:
double exp(long base, long exponent) {
//when the exponent is zero
if (exponent == 0) return 1.0;
long result = base;
long exponent_abs = Math.abs(exponent);
//repeating multiplication many times to achieve exponentiation
for (int i = 2 ; i <= exponent_abs ; ++i) {
result = multiply(result, base);
}
//if the exponent is positive, return result you found.
if (exponent > 0) return result;
//if it is negative, return a fraction.
return 1/((double)result);
}
//repeating addition many times to achieve multiplication.
long multiply(long number1, long number2){
long result = number1;
for (int i = 1; i < number2; ++i){
result += number1;
}
return result;
}
注意函数returns是double值,因为如果你的指数是负数,结果不能用整数类型表示。