NOTE

Integer Power of a Number

Calculate a floating-point number raised to an integer power using repeated multiplication, including negative exponents.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Given a floating-point number base of type double and an integer exponent of type int, calculate base raised to the power of exponent.

It is guaranteed that base and exponent are not both 0.

2. Approach

3. Implementation

func Power(base float64, exponent int) float64 {
	if base == 0 {
		return 0
	}
	if exponent == 0 {
		return 1
	}

	opt := 1
	if exponent < 0 {
		opt = -1
		exponent = - exponent
	}

	data := 1.0
	for i := 0; i < exponent; i++ {
		data = data * base
	}

	if opt == -1 {
		return 1 / data
	}

	return data

}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub