Factorial using recursion in C - recursion

We all know the program for this
int fact(int n)
{
if(n==0)
return(1);
return(n*fact(n-1));
}
But what is not clear to me is how the inner thing is happening?
How is it calculating 5*4*3*2*1 (if n is 5)
Please give a clear explanation on this.
Thanks.....

Mathematically, the recursive definition of factorial can be expressed recursively like so (from Wikipedia):
Consider how this works for n = 3, using == to mean equivalence:
3! == 2! * 3 == (1! * 2) * 3 == ((1) * 2) * 3
This can be derived purely symbolically by repeatedly applying the recursive rule.
What this definition does is first expand out a given factorial into an equivalent series of multiplications. It then performs the actual multiplications. The C code you have performs the exact same way.

What might help to understand it, is that when you are recursively calling the function, the new "cycle" will use N-1, not N.
This way, once you get to N==0, the last function you called will return a 1. At this point all the stack of functions are waiting for the return of the nested function. That is how now you exactly multiply the results of each of the functions on the stack.
In other words, you factorize the number given as input.

Related

Trouble understanding OCAML power function

I'm trying to make sense of this Caml function to calculate the n-th power of a number.
let rec iterate n f d =
if n = 0 then d
else iterate (n-1) f (f d)
let power i n =
let i_times a = a * i in
iterate n i_times 1
I understand what it does conceptually, but I am having trouble understanding the i_times bit.
Per my understanding, i_times takes a value a and returns a*i, whre i is passed onto power upon calling it. In the expression where i_times is defined, it's followed by 1, so wouldn't this mean that i_times 1, all together, is evaluated to 1*i?
In this case, I fail to see how 3 parameters are being passed to iterate. Why doesn't it just end up being 2, that is n and i_times 1?
I know this is a pretty basic function, but I'm just getting started with functional programming and I want to make sense of it.
Basically you're asking how OCaml parses a series of juxtaposed values.
This expression:
f a b c
is iterpreted as a call to a function f that passes 3 separate parameters. It is not parsed like this:
f a (b c)
which would be passing 2 parameters to f.
So indeed, three parameters are being passed to iterate. There are no subexpressions in the list of parameters, just three separate parameters.
Why didn't you figure that the subexpression n i_times would be evaluated before calling iterate? The reason (I suspect) is that you know that n isn't a function. But the parsing of the language doesn't depend on the types of things. If you wrote (n i_times) (with parentheses) it would be parsed as a call to n as a function. (This would, of course, be an error.)

Cumulative Integration Options With Julia

I have two 1-D arrays in which I would like to calculate the approximate cumulative integral of 1 array with respect to the scalar spacing specified by the 2nd array. MATLAB has a function called cumtrapz that handles this scenario. Is there something similar that I can try within Julia to accomplish the same thing?
The expected result is another 1-D array with the integral calculated for each element.
There is a numerical integration package for Julia (see the link) that defines cumul_integrate(X, Y) and uses the trapezoidal rule by default.
If this package didn't exist, though, you could easily write the function yourself and have a very efficient implementation out of the box because the loop does not come with a performance penalty.
Edit: Added an #assert to check matching vector dimensions and fixed a typo.
function cumtrapz(X::T, Y::T) where {T <: AbstractVector}
# Check matching vector length
#assert length(X) == length(Y)
# Initialize Output
out = similar(X)
out[1] = 0
# Iterate over arrays
for i in 2:length(X)
out[i] = out[i-1] + 0.5*(X[i] - X[i-1])*(Y[i] + Y[i-1])
end
# Return output
out
end

Define Piecewise Functions in Julia

I have an application in which I need to define a piecewise function, IE, f(x) = g(x) for [x in some range], f(x)=h(x) for [x in some other range], ... etc.
Is there a nice way to do this in Julia? I'd rather not use if-else because it seems that I'd have to check every range for large values of x. The way that I was thinking was to construct an array of functions and an array of bounds/ranges, then when f(x) is called, do a binary search on the ranges to find the appropriate index and use the corresponding function (IE, h(x), g(x), etc.
It seems as though such a mathematically friendly language might have some functionality for this, but the documentation doesn't mention piecewise in this manner. Hopefully someone else has given this some thought, thanks!
with a Heaviside function you can do a interval function:
function heaviside(t)
0.5 * (sign(t) + 1)
end
and
function interval(t, a, b)
heaviside(t-a) - heaviside(t-b)
end
function piecewise(t)
sinc(t) .* interval(t,-3,3) + cos(t) .* interval(t, 4,7)
end
and I think it could also implement a subtype Interval, it would be much more elegant
I tried to implement a piecewise function for Julia, and this is the result:
function piecewise(x::Symbol,c::Expr,f::Expr)
n=length(f.args)
#assert n==length(c.args)
#assert c.head==:vect
#assert f.head==:vect
vf=Vector{Function}(n)
for i in 1:n
vf[i]=#eval $x->$(f.args[i])
end
return #eval ($x)->($(vf)[findfirst($c)])($x)
end
pf=piecewise(:x,:([x>0, x==0, x<0]),:([2*x,-1,-x]))
pf(1) # => 2
pf(-2) # => 2
pf(0) # => -1
Why not something like this?
function piecewise(x::Float64, breakpts::Vector{Float64}, f::Vector{Function})
#assert(issorted(breakpts))
#assert(length(breakpts) == length(f)+1)
b = searchsortedfirst(breakpts, x)
return f[b](x)
end
piecewise(X::Vector{Float64}, bpts, f) = [ piecewise(x,bpts,f) for x in X ]
Here you have a list of (sorted) breakpoints, and you can use the optimized searchsortedfirst to find the first breakpoint b greater than x. The edge case when no breakpoint is greater than x is also handled appropriately since length(breakpts)+1 is returned, so b is the correct index into the vector of functions f.

Questions on recursion

so I have a few questions on recursions. I am in a class and I am reviewing my notes and text and getting a little confused:
1) Am I getting this correct? Iterators and recursion seem so similar.
Recursion = a function that refers to itself and has a base case to get to the end of the problem.
Iterator: Using ++ or -- to go through all the data to get a piece of information.
2) What is recursive descent ? Is it getting closer to the base case? Then what is recursive ascent?
3) We are given this sample of recursion and it is confusing me:
Product of Positive Integer from 1 to n
Denoted by n! => n! = 1.2.3....(n-2).(n-1).n
0! = 1 , 5! = 1.2.3.4.5 = 120, 6! = 5! . 6 = 720
n! = n . ( n – 1 )!
Definition
– If n = 0 then n! = 1
– If n > 0, then n! = n. (n-1) !
Why is there an exclamation point after (n-1)? What are these dots, like n.(n-1)?
Recursion and iteration are not the same. You can iterate without recursion, and recursion means no iteration.
Let's leave recursive descent for now. That has to do with parsers.
The example is the mathematical operation of taking a factorial. The exclamation point means "factorial". The dot means multiplication.
Remember?
0! = 1
1! = 1
2! = 2*1
3! = 3*2*1 = 3*2!
4! = 4*3*2*1 = 4*3!
and so on.
This is a classic problem to illustrate recursion to undergrads seeing it for the first time:
function factorial_recursion(n) {
if (n <= 1) {
return 1;
} else {
return n*factorial(n-1);
}
}
You can write the same thing without recursion by iterating:
function factorial_iter(n) {
var value = 1;
if (n > 1) {
for (i = 1; i <= n; ++i) {
value *= i;
}
}
return value;
}
Well the dots are multiplication. It is confusing to use dots, but we know 5! = 1*2*3*4*5 so the dots must be multiplication. Also, the ! is the symbol to denote factorial. 5! = 5 * 4!
Yes, iteration and recursion are somehow similar, and it is known that any recursive solution has an equivalent iterative solution and vice versa. However, many problems are much simpler to solve in one of these approaches rather than in the other. The factorial example is easily solvable in both approaches.
Whenever you see how a problem can be reduced to one or more occurrences of the same problem on smaller magnitudes, you can easily proceed with a recursive solution.
I suppose that recursive descent is diving into deeper levels of the recursion, while ascent is the opposite: returning from a call and getting closer to the top level call.
The dots stand for multiplication.

dynamic programming pseudocode for Travelling Salesman

this is a dynamic programming pseudocode for TSP (Travelling Salesman Problem). i understood its optimal substructure but i can't figure out what the code in red brackets do.
i am not asking anyone to write the actual code, i just need explanation on what is happening so i can write my own.... thanks:)
here is a link for the pseudocode, i couln't uploaded over here.
http://www.imagechicken.com/viewpic.php?p=1266328410025325200&x=jpg
Here is some less mathematical pseudo-code. I don't know if this will explain what's happening, but it may help you read it. This isn't a functional algorithm (lots of := all over), so I'm going to use Python pseudo-code.
# I have no idea where 'i' comes from. It's not defined anywhere
for k in range(2,n):
C[set(i,k), k] = d(1,k)
shortest_path = VERY_LARGE_NUMBER
# I have to assume that n is the number of nodes in the graph G
# other things that are not defined:
# d_i,j -- I will assume it's the distance from i to j in G
for subset_size in range(3,n):
for index_subset in subsets_of_size(subset_size, range(1,n)):
for k in index_subset:
C[S,k] = argmin(lambda m: C[S-k,m] + d(G,m,k), S - k)
shortest_path = argmin(lambda k: C[set(range(1,n)),k] + d(G,1,k), range(2,n))
return shortest_path
# also needed....
def d(G, i, j):
return G[i][j]
def subsets_of_size(n, s): # returns a list of sets
# complicated code goes here
pass
def argmin(f, l):
best = l[0]
bestVal = f(best)
for x in l[1:]:
newVal = f(x)
if newVal < bestVal:
best = x
bestVal = newVal
return best
Some notes:
The source algorithm is not complete. At least, its formatting is weird in the inner loop, and it rebinds k in the second argmin. So the whole thing is probably wrong; I've not tried to run this code.
arguments to range should probably all be increased by 1 since Python counts from 0, not 1. (and in general counting from 1 is a bad idea).
I assume that G is a dictionary of type { from : { to : length } }. In other words, an adjacency list representation.
I inferred that C is a dictionary of type { (set(int),int) : int }. I could be wrong.
I use a set as keys to C. In real Python, you must convert to a frozen_set first. The conversion is just busywork so I left it out.
I can't remember the set operators in Python. I seem to remember it uses | and & instead of + and -.
I didn't write subsets_of_size. It's fairly complicated.

Resources