473,811 Members | 3,736 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Recursive Functions

I am trying to write a recursive version of Power(x,n) that works by
breaking n down into halves(where half of n=n/2), squaring
Power(x,n/2), and multiplying by x again if n was odd, and to find a
suitable base case to stop the recursion. Can someone give me an
example of this?

Thanks!
Nov 13 '05
64 7332
On Mon, 27 Oct 2003, Eric Sosman wrote:
"E. Robert Tisdale" wrote:
dmattis wrote:
I am trying to write a recursive version of Power(x,n) that works by
breaking n down into halves(where half of n=n/2), squaring
Power(x,n/2), and multiplying by x again if n was odd, and to find a
suitable base case to stop the recursion.
Can someone give me an example of this?


double Power(double x, unsigned int n) {
return (0 < n)? Power(x, n/2)*Power(x, n - n/2): 1.0;
}


I confess that I considered suggesting this method, but
then decided that wanton cruelty was not (yet) justified.


Well, either that or the interpretation of "suitable base case to
stop the recursion" might need some clarification.

Nov 13 '05 #11

On Tue, 28 Oct 2003, Jarno A Wuolijoki wrote:

On Mon, 27 Oct 2003, Eric Sosman wrote:
"E. Robert Tisdale" wrote:

double Power(double x, unsigned int n) {
return (0 < n)? Power(x, n/2)*Power(x, n - n/2): 1.0;
}


I confess that I considered suggesting this method, but
then decided that wanton cruelty was not (yet) justified.


Well, either that or the interpretation of "suitable base case to
stop the recursion" might need some clarification.


In particular, where is it guaranteed that the base case (n <= 0)
is ever reached? I admit I'm not conversant in the details of
C floating point, but it seems like an unwarrantedly dubious
assumption to be making. What's to say that 1e-100/2 != 1e-100 ?

-Arthur
Nov 13 '05 #12
"Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> wrote:

On Tue, 28 Oct 2003, Jarno A Wuolijoki wrote:

On Mon, 27 Oct 2003, Eric Sosman wrote:
> "E. Robert Tisdale" wrote:
> >
> > double Power(double x, unsigned int n) {
> > return (0 < n)? Power(x, n/2)*Power(x, n - n/2): 1.0;
> > }
>
> I confess that I considered suggesting this method, but
> then decided that wanton cruelty was not (yet) justified.


Well, either that or the interpretation of "suitable base case to
stop the recursion" might need some clarification.


In particular, where is it guaranteed that the base case (n <= 0)
is ever reached? I admit I'm not conversant in the details of
C floating point, but it seems like an unwarrantedly dubious
assumption to be making. What's to say that 1e-100/2 != 1e-100 ?


Err, n is of type unsigned int, thus all divisions are integer
divisions...

Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #13

On Tue, 28 Oct 2003, Irrwahn Grausewitz wrote:

"Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> wrote:
> > "E. Robert Tisdale" wrote:
> >
> > double Power(double x, unsigned int n) {
> > return (0 < n)? Power(x, n/2)*Power(x, n - n/2): 1.0;
> > }


In particular, where is it guaranteed that the base case (n <= 0)
is ever reached? I admit I'm not conversant in the details of
C floating point, but it seems like an unwarrantedly dubious
assumption to be making. What's to say that 1e-100/2 != 1e-100 ?


Err, n is of type unsigned int, thus all divisions are integer
divisions...


Oops. I was thrown by the use of 'double' everywhere else.
Seems silly to use 'double' for the first operand if you're only
going to allow positive integers for the second operand...
plus, in this case Tisdale's solution does exponentially more
work than it really has to. There should be only one call
to Power() within the function itself.

(Proper solution left as an exercise for the OP.)

-Arthur
Nov 13 '05 #14
In article
<Pi************ *************** ********@unix47 .andrew.cmu.edu >,
"Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> wrote:
On Tue, 28 Oct 2003, Irrwahn Grausewitz wrote:

"Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> wrote:
>> > "E. Robert Tisdale" wrote:
> > >
> > > double Power(double x, unsigned int n) {
> > > return (0 < n)? Power(x, n/2)*Power(x, n - n/2): 1.0;
> > > }

In particular, where is it guaranteed that the base case (n <= 0)
is ever reached? I admit I'm not conversant in the details of
C floating point, but it seems like an unwarrantedly dubious
assumption to be making. What's to say that 1e-100/2 != 1e-100 ?


Err, n is of type unsigned int, thus all divisions are integer
divisions...


Oops. I was thrown by the use of 'double' everywhere else.
Seems silly to use 'double' for the first operand if you're only
going to allow positive integers for the second operand...
plus, in this case Tisdale's solution does exponentially more
work than it really has to. There should be only one call
to Power() within the function itself.


I think it does more than exponentially more work than needed...

What is n - n/2 if n is equal to 1?
Nov 13 '05 #15
Irrwahn Grausewitz <ir*******@free net.de> wrote in message news:<p8******* *************** **********@4ax. com>...
"Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> wrote:
On Tue, 28 Oct 2003, Jarno A Wuolijoki wrote:
On Mon, 27 Oct 2003, Eric Sosman wrote:
> "E. Robert Tisdale" wrote:
> >
> > double Power(double x, unsigned int n) {
> > return (0 < n)? Power(x, n/2)*Power(x, n - n/2): 1.0;
> > }
>
> I confess that I considered suggesting this method, but
> then decided that wanton cruelty was not (yet) justified.

Well, either that or the interpretation of "suitable base case to
stop the recursion" might need some clarification.


In particular, where is it guaranteed that the base case (n <= 0)
is ever reached? I admit I'm not conversant in the details of
C floating point, but it seems like an unwarrantedly dubious
assumption to be making. What's to say that 1e-100/2 != 1e-100 ?


Err, n is of type unsigned int, thus all divisions are integer
divisions...


The floating point reference is a red herring. Think about what the
function will do when n is 1.

--
Peter
Nov 13 '05 #16

"James Hu" <jx*@despammed. com> wrote in message
news:x9******** ************@co mcast.com...
On 2003-10-27, dmattis <dm*****@yahoo. com> wrote:
I am trying to write a recursive version of Power(x,n) that works by
breaking n down into halves(where half of n=n/2), squaring
Power(x,n/2), and multiplying by x again if n was odd, and to find a
suitable base case to stop the recursion. Can someone give me an
example of this?
This is not a C question... but the C answer is use pow() (unless you
are purposefully avoiding floating point, in which case a table lookup
is in order).


The algorithm described, in non-recursive form, is commonly used in
languages that supply an integer exponentiation operator. A table
dimensioned INT_MAX-INT_MIN+1 will take up a lot of memory.
<DYOHW> Rewrite your word problem into a recurrence relationship. Use
induction to prove this recurrence correctly calculates x to the nth
power. It should be obvious at that point what your function should
look like and what your base case is. </DYOHW>


Yes, he should do that.

-- glen
Nov 13 '05 #17
On 2003-10-28, Glen Herrmannsfeldt <ga*@ugcs.calte ch.edu> wrote:
"James Hu" <jx*@despammed. com> wrote in message
news:x9******** ************@co mcast.com...
On 2003-10-27, dmattis <dm*****@yahoo. com> wrote:
> I am trying to write a recursive version of Power(x,n) that works by
> breaking n down into halves(where half of n=n/2), squaring
> Power(x,n/2), and multiplying by x again if n was odd, and to find a
> suitable base case to stop the recursion. Can someone give me an
> example of this?
This is not a C question... but the C answer is use pow() (unless you
are purposefully avoiding floating point, in which case a table lookup
is in order).


The algorithm described, in non-recursive form, is commonly used in
languages that supply an integer exponentiation operator.


Yes, but those typically take a floating point type for the x argument,
and an int type for the n argument.
A table dimensioned INT_MAX-INT_MIN+1 will take up a lot of memory.


That is an imaginative approach, but not what I had in mind.

#include <stdint.h>

static int8_t hbit[256] =
{-1
,0
,1,1
,2,2,2,2
,3,3,3,3,3,3,3, 3
,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4 ,4
,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5 ,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5 ,5,5
,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6 ,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6 ,6,6
,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6 ,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6 ,6,6
,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7 ,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7 ,7,7
,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7 ,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7 ,7,7
,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7 ,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7 ,7,7
,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7 ,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7 ,7,7
};

int int_pow(int x, uint8_t n)
{
int t = 1;
if (n == 0) return 1;
if (x == 0) return 0;
switch (hbit[n]) {
case 7: if (n & 1) t *= x; n >>= 1; x *= x;
case 6: if (n & 1) t *= x; n >>= 1; x *= x;
case 5: if (n & 1) t *= x; n >>= 1; x *= x;
case 4: if (n & 1) t *= x; n >>= 1; x *= x;
case 3: if (n & 1) t *= x; n >>= 1; x *= x;
case 2: if (n & 1) t *= x; n >>= 1; x *= x;
case 1: if (n & 1) t *= x; n >>= 1; x *= x;
default: if (n & 1) t *= x;
}
return t;
}

-- James
Nov 13 '05 #18
Christian Bau <ch***********@ cbau.freeserve. co.uk> wrote:
"Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> wrote:
> >> > "E. Robert Tisdale" wrote:
> >> > >
> >> > > double Power(double x, unsigned int n) {
> >> > > return (0 < n)? Power(x, n/2)*Power(x, n - n/2): 1.0;
> >> > > }
<snip> plus, in this case Tisdale's solution does exponentially more
work than it really has to. There should be only one call
to Power() within the function itself.


I think it does more than exponentially more work than needed...

What is n - n/2 if n is equal to 1?


Arrgh, Trollsdale did it again!

And on first glance I thought he actually posted valid code; stupid me.
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #19
Maybe it's just me but doesn't the contrived nature of the function scream
out "Homework Assignment?" Maybe I'm missing something but I just can't see
why you'd ever want to compute this value..

Alea iacta

"Julian V. Noble"

Here is tested C code for raising an integer to an integer power,
recursively. (I hope this isn't a HW assignment but a legitimate
query.)

Nov 13 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1923
by: Magnus Lie Hetland | last post by:
Hi! I've been looking at ways of dealing with nested structures in regexps (becuase I figured that would be faster than the Python parsing code I've currently got) and came across a few interesting things... First there is this, mentioning the (?<DEPTH>) and (?<-DEPTH>) constructs of the .NET regexp matcher: http://www.rassoc.com/gregr/weblog/archive.aspx?post=590
7
567
by: Jon Slaughter | last post by:
#pragma once #include <vector> class empty_class { }; template <int _I, int _J, class _element, class _property> class RDES_T {
7
6133
by: Aloo | last post by:
Dear friends, If we declare a recursive function as 'inline' then does it actually convert to an iterative form during compilation ( the executable code is iterative)? Is it possible ? Please reply.
9
16849
by: Csaba Gabor | last post by:
Inside a function, I'd like to know the call stack. By this I mean that I'd like to know the function that called this one, that one's caller and so on. So I thought to do: <script type='text/javascript'> function myFunc(lev) { // if (lev) return myFunc(lev-1); var aStack=; nextFunc = arguments.callee;
41
3393
by: Harry | last post by:
Hi all, 1)I need your help to solve a problem. I have a function whose prototype is int reclen(char *) This function has to find the length of the string passed to it.But the conditions are that no local variable or global variable should be used.I have to use recursive functions.
5
4947
by: Digital Puer | last post by:
I got this on an interview: Is it possible to write inline recursive functions? I said yes, but there is no guarantee that the compiler will definitely inline your code even if you write "inline". Is this a right answer? It seems to be independent of whether or not the function is recursive. Another question: how can you tell if the compiler has inlined your
10
2573
by: AsheeG87 | last post by:
Hello Everyone! I have a linked list and am trying to include a recursive search. However, I am having trouble understanding how I would go about that. I don't quite understand a recursive search....would any of you be so kind to explain it to me...maybe include some examples. I would GREATLY appreciate it!!!
9
2640
by: pereges | last post by:
Hello I need some ideas for designing a recursive function for my ray tracing program. The idea behind ray tracing is to follow the electromagnetic rays from the source, as they hit the object.The object is triangulated. The rays can undergo multiple reflections, diffractions etc of the same object i.e. a ray hits a surface of the object, undergoes reflection resulting in a reflected ray which can again hit a surface, corner or edge...
3
4246
by: from.future.import | last post by:
Hi, I encountered garbage collection behaviour that I didn't expect when using a recursive function inside another function: the definition of the inner function seems to contain a circular reference, which means it is only collected by the mark-and-sweep collector, not by reference counting. Here is some code that demonstrates it: === def outer():
6
9618
KevinADC
by: KevinADC | last post by:
This snippet of code provides several examples of programming techniques that can be applied to most programs. using hashes to create unique results static variable recursive function serialization The code itself generates a list of strings comprised of random numbers. No number will be repeated within a string, and no string will be repeated within the list of strings. Following the code is a brief discussion of how the above...
0
9731
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10651
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10393
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9208
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7671
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5556
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4342
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3871
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.