Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Calculate x^y – Pow() in Go (Golang)

Posted on March 28, 2020March 28, 2020 by admin

Table of Contents

  • Overview
  • Code

Overview

math package of GO provides a Pow method that can be used to calculate x to the power y.

Below is the signature of the function. It takes input as two float arguments and returns a float

func Pow(x, y float64) float64

The same function can also be used to calculate the square or cube of a number. Just pass the second argument y as 2 in case of square and 3 in case of cube

Code

package main

import (
    "fmt"
    "math"
)

func main() {
    //Power for integers
    res := math.Pow(2, 10)
    fmt.Println(res)

    //Power for float
    res = math.Pow(1.5, 2)
    fmt.Println(res)

    //Anything to power 0 is 1
    res = math.Pow(3, 0)
    fmt.Println(res)
}

Output:

1024
2.25
1
  • go
  • golang
  • power
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme