如何在Java中编写可以计算功率的函数。没有循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19425953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:03:32  来源:igfitidea点击:

How to write a function that can calculate power in Java. No loops

javarepeatexponent

提问by Mo Arctic

I've been trying to write a simple function in Java that can calculate a number to the nth power without using loops.
I then found the Math.pow(a, b)class... or method still can't distinguish the two am not so good with theory. So i wrote this..

我一直在尝试用 Java 编写一个简单的函数,它可以在不使用循环的情况下计算一个数的 n 次方。
然后我发现了Math.pow(a, b)类......或者方法仍然无法区分这两者对理论不太好。所以我写了这个..

public static void main(String[] args) {

    int a = 2;

    int b = 31;

    System.out.println(Math.pow(a, b));

    }

Then i wanted to make my own Math.powwithout using loops i wanted it to look more simple than loops, like using some type of RepeatI made a lot of research till i came across the commons-lang3package i tried using StringUtils.repeat
So far I think this is the Syntax:-

然后我想在不使用循环的情况下制作我自己的Math.pow我希望它看起来比循环更简单,比如使用某种类型的重复我做了很多研究,直到我遇到了我尝试使用StringUtils.repeatcommons-lang3包 到目前为止,我认为这是语法:-

public static String repeat(String str, int repeat)
    StringUtils.repeat("ab", 2);

The problemi've been facing the past 24hrsor more is that StringUtils.repeat(String str, int 2);repeats strings not out puts or numbers or calculations.
Is there anything i can do to overcome this or is there any other better approach to creating a function that calculates powers?
without using loops or Math.pow

问题我已经面临的过去24小时或更多的是,StringUtils.repeat(字符串str,整数2); 重复字符串而不是输出或数字或计算。
有什么我可以做的来克服这个问题,或者有没有其他更好的方法来创建一个计算幂的函数?
不使用循环或 Math.pow

This might be funny but it took me while to figure out that StringUtils.repeatonly repeats strings this is how i tried to overcome it. incase it helps

这可能很有趣,但我花了一段时间才发现StringUtils.repeat只重复字符串,这就是我试图克服它的方式。以防万一它有帮助

 public static int repeat(int cal, int repeat){
     cal = 2+2;
     int result = StringUtils.repeat(cal,2);
     return result;
}  

can i not use recursion maybe some thing like this

我可以不使用递归吗,也许是这样的

public static RepeatThis(String a)
{
     System.out.println(a);
     RepeatThis(a);
} 

just trying to understand java in dept thanks for all your comments even if there were syntax errors as long as the logic was understood that was good for me:)

只是想深入了解 java 感谢您的所有评论,即使存在语法错误,只要理解了对我有好处的逻辑:)

采纳答案by user987339

Try with recursion:

尝试递归:

int pow(int base, int power){
    if(power == 0) return 1;
    return base * pow(base, --power);
}

回答by Jeroen Vannevel

Sure, create your own recursive function:

当然,创建自己的递归函数:

public static int repeat(int base, int exp) {
 if (exp == 1) {
  return base;
 }

 return base * repeat(base, exp - 1);
}

Math.pow(a, b)

Math.pow(a, b)

Mathis the class, powis the method, aand bare the parameters.

Math是类,pow是方法,ab是的参数。

回答by RamonBoza

Use this code.

使用此代码。

public int mypow(int a, int e){
    if(e == 1) return a;
    return a * mypow(a,e-1);
}

回答by Aneesh

A recursive method would be the easiest for this :

递归方法将是最简单的:

int power(int base, int exp) {
    if (exp != 1) {
        return (base * power(base, exp - 1));
    } else {
        return base;
    }
}

where baseis the number and expis the exponenet

在哪里base是数字,exp是指数

回答by myang

This one handles negative exponential:

这个处理负指数:

public static double pow(double base, int e) {
    int inc;
    if(e <= 0) {
        base = 1.0 / base;
        inc = 1;
    }
    else {
        inc = -1;
    }
    return doPow(base, e, inc);
}

private static double doPow(double base, int e, int inc) {
    if(e == 0) {
        return 1;
    }
    return base * doPow(base, e + inc, inc);
}

回答by Vaibhav Fouzdar

Another implementation with O(Log(n)) complexity

另一个复杂度为 O(Log(n)) 的实现

public static long pow(long base, long exp){        
    if(exp ==0){
        return 1;
    }
    if(exp ==1){
        return base;
    }

    if(exp % 2 == 0){
        long half = pow(base, exp/2);
        return half * half;
    }else{
        long half = pow(base, (exp -1)/2);
        return base * half * half;
    }       
}

回答by Gnanodharan Madahvan

Function to handle +/- exponents with O(log(n)) complexity.

处理复杂度为 O(log(n)) 的 +/- 指数的函数。

double power(double x, int n){
 if(n==0)
  return 1;

  if(n<0){
      x = 1.0/x;
      n = -n;
  }
 double ret = power(x,n/2);
 ret = ret * ret;
 if(n%2!=0)
   ret = ret * x;
 return ret;

}

}

回答by Angelo

I think in Production recursion just does not provide high end performance.

我认为在生产递归只是不提供高端性能。

double power(double num, int exponent)
{

double value=1;
int Originalexpn=exponent;
double OriginalNumber=num;

if(exponent==0)
    return value;

if(exponent<0)
{
    num=1/num;
    exponent=abs(exponent);
}

while(exponent>0)
{
    value*=num;
    --exponent;
}

cout << OriginalNumber << " Raised to  " << Originalexpn << " is " << value << endl;
return value;

}

}

回答by Var

Here is a O(log(n)) code that calculates the power of a number. Algorithmic technique used is divide and conquer. It also accepts negative powers i.e., x^(-y)

这是一个计算数字幂的 O(log(n)) 代码。使用的算法技术是分而治之。它还接受负幂,即 x^(-y)

import java.util.Scanner;

public class PowerOfANumber{
        public static void main(String args[]){
                float result=0, base;
                int power;
                PowerOfANumber calcPower = new PowerOfANumber();
                /* Get the user input for the base and power */
                Scanner input = new Scanner(System.in);
                System.out.println("Enter the base");   
                base=input.nextFloat();
                System.out.println("Enter the power");
                power=input.nextInt();
                result = calcPower.calculatePower(base,power);
                System.out.println(base + "^" + power + " is " +result);
        }   
        private float calculatePower(float x, int y){ 
                float temporary;
                /* Termination condition for recursion */    
                if(y==0)
                        return 1;
                temporary=calculatePower(x,y/2);
                /* Check if the power is even */
                if(y%2==0)
                        return (temporary * temporary);
                else{
                        if(y>0)
                                return (x * temporary * temporary);
                        else
                                return (temporary*temporary)/x;
                }    
        }
}