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:
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
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework