Start learning free

LESSON 161 OF 338 · LOOPS - CHALLENGES

Print Powers in Go: Using a Condition-Only for Loop

Practice Read the full explanation

Given two non-negative integers A and B, print to the console all numbers less than or equal to B that are powers of A

Powers of a number are: A0, A1, A2, etc.

An = A multiplied by itself n times

A0 = 1
A1 = A
A2 = A * A
A3 = A * A * A
A4 = A * A * A * A
etc.

Example:

Input: A = 3, B = 100

Output:
1
3
9
27
81

Explanation:
30 = 1
31 = 3
32 = 9
33 = 27
34 = 81
Hints:

We start with the integer 1. We should repeatedly do some instructions (print it then multiply it by A) as long as one condition is satisfied (current power <= B). Sounds familiar?

We should use a variable power, initially equal to 1, in order to store the current power. And we should use a while loop to repeatedly check if power <= B and if so, print and update power. How will the code look like?

power = 1
while power <= B:
	print(power)
	power *= A


STEP 1 OF 4
    Ctrl + Enter to check

    GO · LOOPS - CHALLENGES

    Print Powers in Go, explained

    Problem overview

    The function printPowers receives two non-negative integers, A and B. It prints every power of A that is less than or equal to B, one per line, in increasing order. The powers of A are A⁰ = 1, A¹ = A, A² = A * A, and so on. The function prints its result and returns nothing.

    For A = 3 and B = 100 the powers are 1, 3, 9, 27, 81 and then 243, which is above 100. So the output is:

    1
    3
    9
    27
    81
    

    Approach: multiply and test

    You don't need an exponent or a power function. Start with the smallest power, 1, and get each next power by multiplying the current one by A. As long as the current power is at most B, print it and move on. The first time it exceeds B, every later power is larger still, so you can stop.

    This is a loop whose number of iterations isn't known in advance. It depends on the values, not on a count. In many languages that calls for while. Go has no while, and uses for with only a condition instead.

    Step by step

    1. Start at 1. Declare power with := and give it the value 1, which is A⁰. Every power list starts there, even when A is large.
    2. Loop on a condition. Write a for that has only a condition after the keyword, here power <= B. There is no initialiser and no post statement. This is Go's version of a while loop.
    3. Print the current power with fmt.Println. The check has just passed, so this value belongs in the output.
    4. Advance to the next power. Multiply power by A with *=. Without this step the condition never changes and the loop runs forever.

    The solution in Go

    func printPowers(A int, B int) {
        power := 1
        for power <= B {
            fmt.Println(power)
            power *= A
        }
    }
    

    Some Go details behind these six lines:

    • One loop keyword. Go's for has three forms. for i := 0; i < n; i++ is the classic one, for cond { } is the while replacement used here, and for { } with nothing loops until a break or return.
    • No parentheses, required braces. The condition isn't wrapped in parentheses, and the braces are mandatory, even for a one-line body.
    • := declares and infers. power := 1 creates a variable of type int. Inside the loop, power *= A uses plain assignment, because the variable already exists. Writing := there would be an error, or would create a new variable that shadows the old one if it appeared inside a nested block.
    • Printing needs fmt. fmt.Println comes from the fmt package, which a complete Go file must import. Println ends each value with a newline, which gives one number per line.
    • Integer size. An int is 64 bits here, and overflow wraps around silently instead of raising an error. Inputs of normal size stay far from that limit.

    Complexity

    Time: O(log B) for A ≥ 2. Each iteration multiplies power by at least 2, so the loop can run only about log₂(B) times before power passes B. With B = 100 and A = 3 it runs 5 times.

    Space: O(1). The function keeps one variable, power, whatever the size of B.

    Edge cases and common mistakes

    • B smaller than 1. With B = 0 the condition 1 <= 0 fails at once and nothing is printed. That is right, since the smallest power, 1, is already too large.
    • B equal to a power. For A = 2 and B = 8 the output ends with 8. The comparison is <=, so a power equal to B is included. Using < would drop it.
    • A = 1 and A = 0. With A = 1, power stays 1 forever, so for any B of at least 1 the loop never ends and prints 1 endlessly. With A = 0, power becomes 0 after the first pass and stays there, with the same result. The solution is correct for bases of 2 and up. If your inputs can include 0 or 1, handle them before the loop.
    • Printing after the multiplication. Swapping the two lines inside the loop prints 3, 9, 27, 81, 243 for the example. The value 1 is lost, and 243, which is above B, appears.
    • Forgetting to update. Leaving out power *= A prints 1 forever.

    Testing

    • A = 3, B = 100 prints 1, 3, 9, 27, 81.
    • A = 2, B = 0 prints nothing.
    • A = 5, B = 4 prints just 1.
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free