Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Program to calculate the power of a number

Posted on January 29, 2022January 29, 2022 by admin

Overview

The objective is to calculate the power of a given integer. There will be two inputs

  • The number itself – The number can be positive as well as negative. It can be float as well
  • The power – The power also can be positive as well as negative

Examples

Input: Num:2, Power:4
Output: 16

Input: Num:2, Power:-4
Output: 0.0625

Program

Here is the program for the same.

package main

import "fmt"

func pow(x float64, n int) float64 {

	if x == 0 {
		return 0
	}

	if n == 0 {
		return 1
	}

	if n == 1 {
		return x
	}

	if n == -1 {
		return 1 / x
	}

	val := pow(x, n/2)

	m := x
	if n < 0 {
		m = 1 / x
	}

	if n%2 == 1 || n%2 == -1 {
		return val * val * m
	} else {
		return val * val
	}

}

func main() {
	output := pow(2, 4)
	fmt.Println(output)

	output = pow(2, -4)
	fmt.Println(output)
}

Output

16
0.0625
©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme