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

后端 未结 9 1163
一个人的身影
一个人的身影 2021-01-03 08:28

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...

9条回答
  •  失恋的感觉
    2021-01-03 09:32

    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)

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

提交回复
热议问题