Friday, March 10, 2023
HomeSoftware EngineeringCalculate Powers of Integers in Java

Calculate Powers of Integers in Java


If you’ll want to calculate the powers of Integers in Java, then you are able to do one of many following:

Possibility 1 – Utilizing for loops

public class Energy {
    public static void major(String args[]){
        int quantity = 5;
        int energy = 3;
        int consequence = calculatePower(quantity,energy);
        System.out.println(quantity+"^"+energy+"="+consequence);
    }
    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;
        }
    }
}

Possibility 2 – Utilizing Recursion

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

Possibility 3 – Utilizing Math.pow()

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments