Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Math Exercises: Calculate power of a number without using multiplication and division operators

Java Math Exercises: Exercise-16 with Solution

Write a Java program to calculate power of a number without using multiplication(*) and division(/) operators.

Sample Solution:

Java Code:

import java.util.*;
public class solution {	
  public static int power(int b, int e) 
    { 
        if (e == 0) 
            return 1; 
              
        int result = b; 
        int temp = b; 
        int i, j; 
          
        for (i = 1; i < e; i++) { 
            for (j = 1; j < b; j++) { 
                result += temp; 
            } 
            temp = result; 
        } 
          
        return result; 
    } 
 
   public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Input the base: ");
        int b = scan.nextInt();
		System.out.print("Input the exponent: ");
        int e = scan.nextInt();
        scan.close(); 
		if (b>0 && e>0)
		System.out.println("Power of the number: "+power(b, e));		
		}
 }

Sample Output:

 Input the base:  2
Input the exponent:  5
Power of the number: 32

Flowchart:

Flowchart: Calculate power of a number without using multiplication and division operators.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to multiply two integers without using multiplication, division, bitwise operators, and loops.
Next: Write a Java program to calculate and print average (or mean) of the stream of given numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe