#### Archived

This topic is now archived and is closed to further replies.

# recursive help

This topic is 5813 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have to write a recursive function which takes in two parameters (positive ints) with one representing the base of an exponent and the other the power of the exponent. For example exponentialIt(5, 3) would return 125. Any Ideas where to start?

##### Share on other sites
Well, this is probably a school assignment so I''m not going to make it too easy.

1. The function body must have a base case when the recursion stops. Otherwise it''ll start calling itself forwer. You know that x^0 = 1, so you just have to check that if the second argument is 0, return 1.

2. Then comes the recursion part. You want to move towards the base case, where the second argument is 0. How? By reducing the second argument by one, naturally. Eventually it becomes 0 and the recursion stops. But whenever you reduce the exponent by one, you must do something special....

Ok.. was I vague enough?-)

##### Share on other sites
Where to start, or the function itself? Well here's an idea:

WARNING... complete function follows

EDIT:
Well, nevermind, I took it out. Sorry man, just follow the guy above's tips. It didn't occur to me that it could be an assignment

[edited by - Ronin Magus on November 21, 2002 5:17:49 PM]

##### Share on other sites
PS: That was a joke

PPS: Ronin, that might get you a passing grade, but not an "A". Your algorithm is O(N). There''s a O(lgN) solution.

PPPS: We really shouldn''t help people with their homework.

##### Share on other sites
I say again, Stoffel is a genius

O(log N) solution??? hmmm...I suck at optimization...let me think..

[edited by - Ronin Magus on November 21, 2002 5:21:19 PM]

##### Share on other sites
Yep, thats right, lg2(n). Consider that exponentiation is reallly like adding, so we want to know how many steps it takes to get to k, where in each step we multiply by some previous result. to get 17 for example, you get:
x, x*x, x^4, x^8, x^16, x^17, and for any exponent k, it will take at most 2lg2(k) -1 one steps. Stoffel, is this algorithm recursive though?
Brendan

##### Share on other sites
After pulling my hair out, I cheated and looked it up on the internet. I''d have never thought of that myself anyway

http://roninmagus.hopto.org
acronymfinder.com - Find any acronym you need!

##### Share on other sites
quote:
Original post by Punty50
Stoffel, is this algorithm recursive though?
Any loop can be made recursive.

##### Share on other sites
quote:
Original post by Stoffel

heh heh heh

1. 1
Rutin
47
2. 2
3. 3
4. 4
5. 5

• 13
• 10
• 12
• 10
• 13
• ### Forum Statistics

• Total Topics
632994
• Total Posts
3009769
• ### Who's Online (See full list)

There are no registered users currently online

×