fast power function in scala - scala

I tried to write a function for fast power in scala, but I keep getting java.lang.StackOverflowError. I think it has something to do with two slashes that use in the third line when I recursively called this function for n/2.
Can someone explain why is this happening
def fast_power(x:Double, n:Int):Double = {
if(n % 2 == 0 && n > 1)
fast_power(x, n/2) * fast_power(x, n /2)
else if(n % 2 == 1 && n > 1)
x * fast_power(x, n - 1)
else if(n == 0) 1
else 1 / fast_power(x, n)
}

Your code doesn't terminate, because there was no case for n = 1.
Moreover, your fast_power has linear runtime.
If you write it down like this instead:
def fast_power(x:Double, n:Int):Double = {
if(n < 0) {
1 / fast_power(x, -n)
} else if (n == 0) {
1.0
} else if (n == 1) {
x
} else if (n % 2 == 0) {
val s = fast_power(x, n / 2)
s * s
} else {
val s = fast_power(x, n / 2)
x * s * s
}
}
then it is immediately obvious that the runtime is logarithmic, because
n is at least halved in every recursive invocation.
I don't have any strong opinions on if-vs-match, so I just sorted all the cases in ascending order.

Prefer the match construct instead of multiple if/else blocks. This will help you isolate the problem you have (wrong recursive call), and write more understandable recursive functions. Always put the termination conditions first.
def fastPower(x:Double, m:Int):Double = m match {
case 0 => 1
case 1 => x
case n if n%2 == 0 => fastPower(x, n/2) * fastPower(x, n/2)
case n => x * fastPower(x, n - 1)
}

Related

Facing Issues in Recursion of Perfect Number Problem

I've been working on the scala recursion problem. I used to develop the program using loops and then use the concept of recursion to convert the existing loop problem in a recursive solution.
So I have written the following code to find the perfect number using loops.
def isPerfect(n: Int): Boolean = {
var sum = 1
// Find all divisors and add them
var i = 2
while ( {
i * i <= n
}) {
if (n % i == 0) if (i * i != n) sum = sum + i + n / i
else sum = sum + i
i += 1
}
// If sum of divisors is equal to
// n, then n is a perfect number
if (sum == n && n != 1) return true
false
}
Here is my attempt to convert it into a recursive solution. But I'm getting the incorrect result.
def isPerfect(n: Int): Boolean = {
var sum = 1
// Find all divisors and add them
var i = 2
def loop(i:Int, n:Int): Any ={
if(n%i == 0) if (i * i != n) return sum + i + n / i
else
return loop(i+1, sum+i)
}
val sum_ = loop(2, n)
// If sum of divisors is equal to
// n, then n is a perfect number
if (sum_ == n && n != 1) return true
false
}
Thank you in advance.
Here is a tail-recursive solution
def isPerfectNumber(n: Int): Boolean = {
#tailrec def loop(d: Int, acc: List[Int]): List[Int] = {
if (d == 1) 1 :: acc
else if (n % d == 0) loop(d - 1, d :: acc)
else loop(d - 1, acc)
}
loop(n-1, Nil).sum == n
}
As a side-note, functions that have side-effects such as state mutation scoped locally are still considered pure functions as long as the mutation is not visible externally, hence having while loops in such functions might be acceptable.

Check if number is prime in O(sqrt(n)) in Scala

When checking if n is a prime number in Scala, the most common solutions is concise one-liner which can be seen in almost all similar questions on SO
def isPrime1(n: Int) = (n > 1) && ((2 until n) forall (n % _ != 0))
Moving on, it's simple to rewrite it to check only odd numbers
def isPrime2(n: Int): Boolean = {
if (n < 2) return false
if (n == 2) return true
if (n % 2 == 0) false
else (3 until n by 2) forall (n % _ != 0)
}
However, to be more efficient I would like to combine checking only odds with counting up to sqrt(n), but without using Math.sqrt. So, as i < sqrt(n) <==> i * i < n, I would write C-like loop:
def isPrime3(n: Int): Boolean = {
if (n < 2) return false
if (n == 2) return true
if (n % 2 == 0) return false
var i = 3
while (i * i <= n) {
if (n % i == 0) return false
i += 2
}
true
}
The questions are:
1) How to achieve the last version in the first version nice Scala functional style?
2) How can I use Scala for to this? I thought of something similar to below, but don't know how.
for {
i <- 3 until n by 2
if i * i <= n
} { ??? }
Here is a method to verify if n is prime until sqrt(n) without using sqrt:
def isPrime3(n: Int): Boolean = {
if (n == 2) {
true
} else if (n < 2 || n % 2 == 0) {
false
} else {
Stream.from(3, 2).takeWhile(i => i * i < n + 1).forall(i => n % i != 0)
}
}
If you want to do it until n/2, which is also a possible optimization (worse than sqrt(n)), you can replace the last line with:
(3 to n/2 + 1 by 2).forall(i => n % i != 0)
If you prefer, you could also make a tail recursive version, something along these lines:
import scala.annotation.tailrec
def isPrime3(n: Int): Boolean = {
if (n == 2 || n == 3) {
true
} else if (n < 2 || n % 2 == 0) {
false
} else {
isPrime3Rec(n, 3)
}
}
#tailrec
def isPrime3Rec(n:Int, i: Int): Boolean = {
(n % i != 0) && ((i * i > n) || isPrime3Rec(n, i + 2))
}

Scala: IndexOutOfBoundsException: -1

I went step by step looking at this function and it seems to me that it should avoid calling sortedCoins(0-1) by using only sortedCoins(0) and terminating when y == -1, but somehow it doesn't. Why?
def countChange(amount: Int, coins: List[Int]): Int = {
var x = coins.length
var y = x
val sortedCoins = coins.sortWith(_ < _)
def cc(amount: Int, x: Int): Int = {
y -= 1
if (amount == 0) 1
else if (y == 0) cc(amount - x, sortedCoins(y))
else if (amount < 0 || y == -1) 0
else cc(amount, sortedCoins(y - 1)) + cc(amount - x, sortedCoins(y))
}
cc(amount, x)
}
You need to rethink way in which you are writing this algorithm. You see your y variable is "global" scope in your recursive function, when you execute your function it will go to
cc(amount, sortedCoins(y - 1)) + cc(amount - x, sortedCoins(y))
multiple times, and it will execute first side of equation and it will decrement y every time. Then, y will become 0 and your
else if (y == 0) cc(amount - x, sortedCoins(y))
line will be executed, next because y=-1 your
else if (amount < 0 || y < 0) 0
line will be executed. And here we come to exception, because this line returned 0, recursively second part of equation of last else will be executed, which is
cc(amount - x, sortedCoins(y))
, and right now y=-1, that is why you have this exception. I hope this is understandable.

Do if else statements in Scala always require an else?

I have the following function which works fine:
def power(x: Double, n: Int) : Double = {
if (n > 0 && n % 2 == 0) power(x, n/2) * power(x, n/2)
else if (n > 0 && n % 2 == 1) x * power(x, n-1)
else if (n < 0) 1 / power(x, -n)
else 1
}
If I change it to be:
def power(x: Double, n: Int) : Double = {
if (n > 0 && n % 2 == 0) power(x, n/2) * power(x, n/2)
else if (n > 0 && n % 2 == 1) x * power(x, n-1)
else if (n < 0) 1 / power(x, -n)
else if (n==0 ) 1
}
I.e. change the final else statement to be an else if, then I get the following error trying to call the function:
> <console>:8: error: not found: value power
power(2, 1)
^
I'm guessing this is because there is a possible return type of Unit because the value of n could meet none of the conditions?
In Java "if-else" is a statement. In Scala it is an expression (think of Java's ternary ?:), meaning that it always produces some value. As mentioned by som-snytt in comments, in case of a missing else block the compiler supplies else (), which is of type Unit, which obviously conflicts with the expected type Double in your example.
Some valid examples of missing else are provided in Chris's answer.
No - In general, an if expression does not require an else clause.
Examples:
if (true) println("a")
// prints "a"
if (false) println("a") else if (true) println("b")
// prints "b"
As Nikita Volkov's answer says, though, it is necessary if you need the expression to have some type other than Unit.
Your guess is correct. The method must return a Double, yours would return Unit if non of the "if.." cases match. Actually, when you paste the second definition into the repl, you should get
<console>:11: error: type mismatch;
found : Unit
required: Double

Parenthesis Balancing in Scala

Here is my problem: I don't understand how the code works.
How does "())(" return false?
def balance(chars: List[Char], numOpens: Int): Boolean = {
if (chars.isEmpty) {
numOpens == 0
} else {
val h = chars.head
val n =
if (h == '(') numOpens + 1
else if (h == ')') numOpens - 1
else numOpens
if (n >= 0) balance(chars.tail, n)
else false
}
}
The lines:
if (n >= 0) balance(chars.tail, n)
else false
mean that if at any point there are any unbalanced ) characters, false will be returned immediately (n will be < 0). For the specific example you give: ())( we can follow how the value of n varies as the function works through the string:
First character - (: n -> 1, continue check using remaining characters: ))(
Second character - ): n -> 0, continue check using remaining characters: )(
Third character - ): n -> -1, else triggered - return false immediately. The fourth character is never checked.
Shadowlands's answer is correct, but I hope you'll find this more demonstrative:
Let's imagine we are on the top upper stair of infinite stairway. And there is an instruction: ( means step down (↓), ) means step up (↑) and you should ignore all other instructions.
val n =
if (h == '(') numOpens + 1 // step down
else if (h == ')') numOpens - 1 // step up
else numOpens // ignore
After the last step we have to stand on the top upper stair. Otherwise instruction is invalid.
if (chars.isEmpty) {
numOpens == 0
} else { ... }
You can't make a step up from the top upper stair, otherwise instruction is invalid.
if (n >= 0) ...
else false // there is no stairs upper than the upper one (0)
Example:
())( means ↓↑↑↓. After this part ↓↑ you'll be on the top upper stair, so you can't make step up after next command (↑) (n < 0), so the instruction is invalid.