Problem overview
The method printPowers(A: Int, B: Int) must print every power of A that is less than or equal to B, one per line, starting with A to the power 0, which is 1. It returns nothing: the output is what the lesson's tests look at.
For A = 3 and B = 100 the powers are 1, 3, 9, 27 and 81. The next one, 243, is more than 100, so the method stops there.
Approach
You do not need an exponent or a power function. Each power is the previous one multiplied by A, so keep a single variable power that starts at 1. While it is no more than B, print it and multiply it by A. We do not know in advance how many iterations will be needed, which makes while a better fit than a for loop over a fixed range.
Step by step
- Declare
poweras avarset to 1. The loop changes it, sovalwould not compile. Scala infersIntfrom the literal. - Write a
whileloop whose condition ispower <= B. The condition is checked before each pass, so a value aboveBis never printed. - Print
powerwithprintln, which puts each value on its own line. - Update
powerto the next power ofAwithpower *= A. Without this line the loop would print the same number forever.
The solution in Scala
class Solution {
def printPowers(A: Int, B: Int): Unit = {
var power = 1
while (power <= B) {
println(power)
power *= A
}
}
}
Some Scala details:
Unitreturn type. The method prints and returns nothing useful, which Scala writes asUnit. The body's last expression is thewhileloop, which also has typeUnit, so noreturnis needed.varversusval.valcannot be reassigned. A variable that a loop updates must bevar.*=. Scala has no++, but it has compound assignments such as+=and*=.power *= Ameanspower = power * A.- Parentheses on the condition. A
whilecondition goes in parentheses, and the braces hold the body.
Complexity
Time: O(log B). The value of power is multiplied by A each pass, so it grows geometrically, and the loop ends after about log of B to the base A iterations. For A = 2 and B = 1000000 that is 20 prints.
Space: O(1). Only power is stored.
Edge cases and common mistakes
Bless than 1. WithB = 0the condition is false at the start, so nothing is printed. This is correct, because evenAto the power 0 is 1, which is more than 0.A = 1.powerstays at 1, so the loop never ends for anyBof at least 1.A = 0also loops forever whenBis at least 1, becausepowerdrops to 0 after the first print and stays there. The solution assumesAis at least 2, as in the example.- Overflow.
Intis 32 bits and overflow wraps silently. IfBis close toInt.MaxValue,power *= 2eventually wraps to a negative number, which is still<= B, so the loop keeps printing instead of stopping. Use aLongforpowerif the bounds can be that large. - Printing after multiplying. Swapping the two lines in the loop prints 3, 9, 27, 81, 243 and misses the first power, 1.
- Using
<instead of<=. A power equal toBmust be printed: forA = 3andB = 27the last line is 27.
Testing
A = 3,B = 100prints 1, 3, 9, 27, 81.A = 2,B = 0prints nothing.A = 5,B = 1prints 1.
