Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to find the power of a number efficiently in Java?

public class EfficientPower {
	/*
	 * Aim is to find the power of a number
	 * in an efficient manner.
	 * Let us denote the exponent by n.
	 * Time complexity: O(log2(n))
	 * Space complexity: O(1)
	 */
	public static void main(String[] args) {
		double base = 10;
		int exponent = 2;
		System.out.println(fastPower(base, exponent)); // 100.0
	}

	// Method for efficiently calculating power
	private static double fastPower(double base, int exponent) {
		if (exponent == 0) {
			return 1;
		}
		// If exponent is negative, take reciprocal of base
		// and change sign of the exponent.
		if (exponent < 0) {
			base = 1 / base;
			exponent = -exponent;
		}
		double answer = 1;
		// Update answer based on binary
		// representation of exponent
		while (exponent != 0) {
			// If bit is 1, update answer
			if (exponent % 2 == 1)
				answer = answer * base;
			// If bit is 0, move to next bit
			base = base * base;
			exponent = exponent / 2;
		}

		return answer;
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: address book java program to add edit and delete 
Java :: Java program to find the sum of all even numbers from 1 to 10 
Java :: java key pressed 
Java :: character classes in regex 
Java :: go to activity android 
Java :: How to efficiently find the middle node of a singly linked list, in Java? 
Java :: open a new activity on click of a button 
Java :: rates api 
Java :: java intercept ctrl c 
Java :: remove action bar android studio 
Java :: java socket get ip address of client 
Java :: cors filter spring boot 
Java :: how to compare 3 numbers in java 
Java :: java get unix timestamp 
Java :: java multiplication table nested loop 
Java :: print colored text java 
Java :: java round double to 2 decimals 
Java :: how to extract decimal vqalue from float in android studio 
Java :: input date in java 
Java :: status codes springboot 
Java :: hashtable contains key java 
Java :: Multiply two Strings Leetcode 
Java :: spigot despawn entity 
Java :: java regex ip 
Java :: hibernate create query count return 
Java :: sprint jpa properties for application.yml 
Java :: char equals java 
Java :: hanoi tower java 
Java :: java parallel sort 
Java :: space in java 
ADD CONTENT
Topic
Content
Source link
Name
7+1 =