Software Engineering

The right way to Calculate Powers of Integers in Java

The right way to Calculate Powers of Integers in Java
Written by admin


If it is advisable to calculate the powers of Integers in Java, then you are able to do one of many following:

Choice 1 – Utilizing for loops

public class Energy {
    public static void foremost(String args[]){
        int quantity = 5;
        int energy = 3;
        int end result = calculatePower(quantity,energy);
        System.out.println(quantity+"^"+energy+"="+end result);
    }
    static int calculatePower(int num, int energy){
        int reply = 1;
        if (num > 0 && energy==0){
            return reply;
        } else if(num == 0 && energy>=1){
            return 0;
        } else{
            for(int i = 1; i<= energy; i++)
                reply = reply*num;
            return reply;
        }
    }
}

Choice 2 – Utilizing Recursion

public class Energy {
    public static void foremost(String args[]){
        int quantity = 3;
        int energy = 3;
        int end result = CalculatePower(quantity,energy);
        System.out.println(quantity+"^"+energy+"="+end result);
    }
    static int CalculatePower (int num, int pow){
        if (pow == 0)
            return 1;
        else
            return num * CalculatePower(num, pow - 1);
    }
}

Choice 3 – Utilizing Math.pow()

import java.lang.Math;
public class Energy {
    public static void foremost(String args[]){
        int quantity = 6;
        int energy = 3;
        double end result = CalculatePower(quantity,energy);
        System.out.println(quantity+"^"+energy+"="+end result);
    }
    static double CalculatePower (int num, int pow){
        return Math.pow(num,pow);
    }
}

About the author

admin

Leave a Comment