简体   繁体   English

在Java中仅使用加法进行指数运算

[英]Doing exponential operation using only addition in Java

I'm having trouble making this program. 我在制作此程序时遇到了麻烦。 Is it possible to write a program by getting the exponential value without using *, ^, Math.pow ? 是否可以通过获取指数值而不使用*, ^, Math.pow来编写程序? Example I have base of 2 and the exponent is 3. 示例我的底数为2,指数为3。

Q1. Q1。 what operation should I used to help the addition to come up with the correct result? 我应该使用什么操作来帮助加法得出正确的结果?

Q2. Q2。 addition is enough? 加法够吗?

Yes, it is possible to only use addition to do exponentiation. 是的,可以仅使用加法进行求幂。 Remember that multiplication is the repetition of addition many times, and that exponentiation is the repetition of multiplication many times. 请记住,乘法是多次加法的重复,而幂是多次乘法的重复。

For example, you could write the following function that will exponentiate a number: 例如,您可以编写以下函数以对数字取幂:

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;
 }

Note that the function returns a double value, since if your exponent is negative, the result cannot be expressed with an integral type. 请注意,该函数返回一个双精度值,因为如果您的指数为负,则结果不能用整数类型表示。

Why can't you use those functions of the language? 您为什么不能使用语言的那些功能? Anyway: 无论如何:

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;
}

This obviously only works for integers (or longs really), if you have a floating value as exponent I dont think you can avoid ^ or Math.pow 显然,这仅适用于整数(或实际上是long),如果您将浮点值作为指数,我认为您可以避免^或Math.pow

Note that I have not tested this but should work along the line of this, I might have messed up somewhere. 请注意,我尚未对此进行测试,但应该按照此思路进行工作,否则我可能会陷入困境。

You should also note thate x^0=1, so add an extra check there. 您还应注意x ^ 0 = 1,因此在此处添加额外的检查。 And this only works with signed ints, as this algorithm is not made for negatives 而且这仅适用于带符号的整数,因为此算法不适用于负数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM