In SML - Why doesn't simple recursion always return 0 if first expression met? - recursion

In a simple recursion with first if expression true then 0. if steps in the recursion keeps going until that first expression is true, why isn't 0 always returned?
fun stepping (n : int, number : int) =
if number > n
then 0
else 1 + stepping (n, number + 1)
It seems like the function stepping should add one onto number until number > n and then always return 0. Instead, it returns the number of times you went through the recursion cycle until number becomes greater than n.
The above code tests good in SML and gave me what I wanted - the number of steps incrementing by 1 until input "number" is greater than the input "n". But manually walking through the recursion steps, it seems like the return should always be 0 when the incremented "number" > the input "n". What am I missing?

I think you're mistaking the result of the final call to stepping in the recursive chain (which will always be zero) as being the ultimate value returned by the expression, but that is not the case. It is actually part of a larger equation that makes up the overall returned value.
For example, if we look at how the expression gets built up as each recursive call is made when evaluating stepping(3, 1), you end up with...
result = stepping(3, 1)
result = 1 + stepping(3, 2)
result = 1 + 1 + stepping(3, 3)
result = 1 + 1 + 1 + stepping(3, 4)
result = 1 + 1 + 1 + 0
result = 3

Let's say that I'm going to give you some money this year, according to this scheme:
you get nothing on the first of January
on all other days, you get one dollar more than I would have given you the day before
How much would I have to pay you today, the 20th of February?
Fifty dollars or nothing at all?
If you follow the calendar backwards, you will eventually reach January 1st, where the payment is zero, so would you expect to get nothing?
To answer your immediate question: the function does always return 0 if the first condition is met – that is, if number > n.
However, if the first condition isn't met – number <= n – it does not return 0 but 1 + stepping (n, number + 1).
It works exactly like of you called a function with a different name; that function computes a value and then this function adds 1.
It's not like returning a value from inside a loop, such as (pseudocode)
while (true)
{
if number > n
return 0
else
number = number +1
}
which is perhaps what you're thinking about.

Related

Formula for "overflow subtraction"

Say I'm incrementing or decrementing an index which I'll use to move through an array.
The array starts at index 0, and ends at index 4. If I'm at index 0 and want to move back 1 index, I should end up at index 4 (wraps around).
This is probably extremely simple, but for some reason I just can't come up with a formula that would give me this result. "wrap around addition" was pretty straight forward: index % 5 + 1, but I just can't figure out subtraction.
The correct formula for addition is (index + 1) % 5. Your version gives the wrong result when index is 4.
The correct formula for subtraction depends on the behaviour of the % operator in the language you're using:
In Python, (index - 1) % 5 is correct because % guarantees a result between 0 and 4 inclusive even when the left-hand-side is negative.
In C and Java, (index + 4) % 5 is correct, because % would return a negative remainder when the left-hand-side is negative. Note that this formula would also work in Python.
For more discussion see this other Q&A.
Formula
newindex = (index + increment + arraylen) % arraylen
works for increments +1 and -1 (forward and backward moving).
arraylen = 5 in your example

Incrementation with a for loop

x <- c(2,5,4,3,9,8,11,6)
count <- 0
for (val in x) {
if (val %% 2 == 0) {
count <- count + 1
}
} print(count)
# [1] 4
I do not get why it is 4 and not 5, could someone give me a hint?
So from x <-c(2,5,4,3,9,8,11,6), there are only four numbers in which the remainder will be 0 when divided by 2.
Knowing that, let's look at what each part of the code does. You are defining a variable count and assigning it the value of 0. Already from the beginning, count starts at 0. The next line is a for loop. What the loop does is go through each value of x (recall that x <-c(2,5,4,3,9,8,11,6)). Now, the if statement says that for each value of x, if the value is divisible by 2 and has no remainder, add 1 to count (which is why you have the line count <- count + 1, you are adding 1 to count, which started at zero, and reassigning the new value to count - think of it as rewriting the value of count, replacing it). Now there are four values in x that are divisible by 2 and have a remainder of zero, so doing the math: 0 + 4 = 4. You should get:
print(count)
[1] 4
Hope this helps explain every aspect of the code. I highly recommend you understand and read about for loops, if statements, and overall just any R basics. There are several tutorials online explaining all these components.

How many times does this recursive function iterate?

I have a recursive function, as follows, where b >= 0
def multiply(a,b):
if b == 0:
return 0
elif b % 2 == 0:
return multiply(2*a, b/2)
else:
return a + multiply(a, b-1)
I would like to know how many times the function will run in terms of a and b.
Thanks.
If binary representation of b (call it B) ends with 1, like xxxx1 than next call to multiply has B = xxxx0.
If B ends with 0, like xxxx0 than next value of B is xxxx.
With that, digit of binary representation of b adds one call if it is 0, and two calls if it is 1. Summing that total number of calls equals to length of initial B + number of ones in initial B.
I might be wrong here, but I think your function does not work the way you intend it. In recursion the most important thing as a propper ending criteria, since it will run forever elseways.
Now your ending criteria is a==0, but with each recursive call you do not decrease a. Just make a pen & paper simulation with a=5 and check if it would stop at any point.

Recursion Confusion - Summation Symbol

I have an assignment with this symbol on it: [Image of unfamiliar symbol
Basically the question asks "Write a recursive Java method which, given a positive integer n, computes and returns the sum of the integers from 1 to n as follows".
I do not need any help on the recursion itself, I really just need to understand what that symbol means (Link Included), so I can answer the question properly.
My Question: What meaning does the symbol possess? What is my instructor expecting as a valid response?
NOTE: I do NOT want anyone to attempt to answer the actual assignment question. I ONLY want know understand what the symbol being used means and what should be returned in my recursion method.
IT is the sigma symbol which means take the sum from i = 1 to n.
so your output comes as 1 + 2 + 3 + ..... + n
This explanation is to left hand side of the equation. others are the same.
It's a summation symbol
The sum of each i starting from i = 1 to i == n equals the sum of each i starting from i = 1 to i == n/2 plus the sum of of each i starting from i = n/2 + 1 to i == n

counting number of arithmetic progressions in an array

My previous qs. was unclear so I am again putting it in clear terms.
I need an efficient algorithm to count the number of arithmetic progressions in a series. The number of elements in a single AP should be >2.
eg. if the series is {1,2,2,3,4,4} then the different solutions are listed below(with index numbers):
0,1,3
0,2,3
0,1,3,4
0,1,3,5
0,2,3,4
0,2,3,5
hence the answer should be 6
I am not able to code it when these numbers become large and size of array increases. I need an efficient algorithm for this.
First of all, you answer is incorrect. Numbers 2,3,4 (indexes also 2,3,4) form an AP.
Second, here is a simple brute force algorithm:
def find (vec,value,start):
for i from start to length(vec):
if vec[i] == value:
return i
return None
for i from 0 to length(vec) - 2:
for j from i to length(vec) - 1:
next = 2 * vec[j] - vec[i] # the next element in the AP
pos = find(vec,next,j+1)
if pos is None:
continue
print "found AP:\n %d\n %d\n %d" % (i,j,pos)
prev = vec[j]
here = next
until (pos = find(vec,next = 2*here-prev,pos+1)) is None:
print ' '+str(pos)
prev = here
here = next
I don't think you can do better than this O(n^4) because the total number of APs to be printed is O(n^4) (consider a vector of zeros).
If, on the other hand, you want to only print maximal APs, i.e., APs which are not contained in any other AP, then the problem becomes much more interesting...

Resources