HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoMinor

Fast power in Go

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fastpowerstackoverflow

Problem

I just started learning Go. To start playing with it, I've implemented the fast power algorithm:

Any suggestions or criticisms regarding the coding style?

package main

import (
    "errors"
    "fmt"
    "math"
)

func main() {
    result, ok := fast_power(2, 4)
    if ok != nil {
        fmt.Println("Something went wrong", ok)
    }
    fmt.Println(result)
}

func fast_power(n uint32, power int) (uint32, error) {

    if power  0; power, factor = power>>1, factor*factor {
        if power&1 == 1 {
            mul(factor)
        }
    }

    return result, nil
}

Solution

If an error type is returned, then the variable you're assigning it to, usually is called err or something similar. An example is shown here.

If instead, a bool type is returned, which is true upon success, then it is called ok. An example is shown here.

You might know that your fast_power function doesn't like getting negative power values, but since I can easily compute 5^(-2), I'm sure there'll be someone who will try to do so with your function. I suggest you document that as well (by means of comments), and not just by throwing an error.

Context

StackExchange Code Review Q#75837, answer score: 2

Revisions (0)

No revisions yet.