Reputation:
algorithm
fun(n)
if n==1 or n==2
return 1
else
return fun(1)+fun(2)+...+fun(n-1)
my code
def fun(n):
sum = 0
if n == 1 or n == 2:
return 1
else:
for i in range(n):
sum += fun(i)
return sum
I am trying to express the following algorithm as a recursive function, but I wonder if my code is a recursive function. If it is not a recursive function, how do we modify the code to make it a recursive function?
Upvotes: 0
Views: 614
Reputation: 1270
Other Generic approach to recursive algorithm will be something like below. Assumption here is the power is calcualated only of positive numbers.
func powerFunc(power, number){
if power == 0 || number ==1 {
return 1
}
return number* powerFunc(power-1,number)
}
From the algorithm OP provided in question if we provide n=2
considering 2^2
is 4. The algorithm returns wrong answer as 1.
Upvotes: 1