Go Program to Calculate the Power of a Number

1. Introduction

Raising a number to a power, also known as exponentiation, is a common mathematical operation. In this post, we'll explore how to perform this operation in Go, showcasing a straightforward and efficient method to calculate the power of a number.

2. Program Overview

Our Go program will:

1. Introduce two numbers: a base and an exponent.

2. Compute the result by raising the base to the power of the exponent.

3. Display the result value to the user.

3. Code Program

// Declaring the package name
package main

// Importing the fmt package for input-output operations
import "fmt"

// Function to compute the power of a number
func Power(base, exponent int) int {
    result := 1
    
    for exponent > 0 {
        if exponent%2 == 1 {
            result *= base
        }
        base *= base
        exponent /= 2
    }
    
    return result
}

// Main function to execute the program
func main() {
    var base, exp int
    fmt.Print("Enter the base: ")
    fmt.Scan(&base)
    fmt.Print("Enter the exponent: ")
    fmt.Scan(&exp)

    // Calculating the power using the Power function
    result := Power(base, exp)
    fmt.Printf("%d raised to the power %d is: %d\n", base, exp, result)
}

Output:

Suppose you input 2 as the base and 3 as the exponent. You can expect the following output:
Enter the base: 2
Enter the exponent: 3
2 raised to the power 3 is: 8

4. Step By Step Explanation

1. Starting the Program: We start by declaring the package and importing the necessary libraries.

2. Power Calculation: Within the Power function, we use a loop to calculate the power of a number. This is an efficient method using the square-and-multiply approach, which takes advantage of the binary representation of the exponent.

3. Program Flow: The main function prompts the user to enter a base and an exponent. It then calls the Power function to compute the result and displays the output using fmt.Printf.

This approach not only ensures the accurate calculation of the power but also performs it in a time-efficient manner.

Comments