Reputation: 33
I am trying to take this working recursive function (below)...
def cubeIt(n: Int): Int = {
println("acc:"+acc);
println("n: "+n);
if(n==0){
return 0;
}
else if(n>0){
return cubeIt(n-1) + 3*(n*n) - 3*n + 1
}
else{
return cubeIt(n+1) - 3*(n*n) - 3*n - 1
}
}
...and turn it into a tail-recursion function.
import scala.annotation.tailrec
@tailrec
def cubeItHelper(n: Int, acc: Int): Int = { /* Implement cubeIt as a tail recursion */
if(n==0){
return acc;
}
if(n>0){
return cubeItHelper(n-1, acc+(3*(n*n) - 3*n + 1));
}
else{
return cubeItHelper(n+1, (acc+((-3)*(n*n) - 3*n - 1)));
}
}
/*-
This is the main function that the users will use.
It should call the helper with the correct initial value of acc argument.
Just replace the ??? with the correct initial value for the acc argument.
-*/
def cubeItTail(n: Int): Int = {
if(n==0){
return 0;
}
else{
cubeItHelper(n, 0);
}
}
With the above code it outputs this:
acc:0
n: 5
acc:61
n: 4
acc:98
n: 3
acc:117
n: 2
acc:124
n: 1
......
first four test lines complete correctly
n: -100
acc:-29701
n: -99
acc:-58808
n: -98
acc:-87327
...(goes forever)
These are the test statements (it's hung up on the final one):
assert(cubeItTail(5) == 125)
assert(cubeItTail(-5) == -125)
assert(cubeItTail(-3) == -27)
assert(cubeItTail(0) == 0)
assert( (-100 to 100).forall( x => (cubeItTail(x) == x * x * x)), "Test Passed!")
I'd appreciate it if anyone could tell me what I am doing wrong here.
Upvotes: 2
Views: 209
Reputation: 33
The print statements
println("acc:"+acc);
println("n: "+n);
in the helper function were causing Jupyter Notebook to crash. They may run fully in a different environment, however. Just take note there will be a lot of print statements.
Upvotes: 1
Reputation: 507
The parameter to cubeItTail
could be negative, in which case you would need to pass in -1 to cubeItHelper
:
def cubeItTail(n: Int): Int = {
if (n == 0) {
return 0;
}
else if (n > 0) {
cubeItHelper(n, 1);
}
else {
cubeItHelper(n, -1);
}
}
Upvotes: 0