Re: Recursive Functions

From: Richard Heathfield (dontmail_at_address.co.uk.invalid)
Date: 10/27/03


Date: Mon, 27 Oct 2003 18:51:28 +0000 (UTC)

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?

/*
   untested,
   unreadable,
   unambitious,
   unenthusiastic
 */
#define k \
unsigned char
k Power(k x,k
n){k r=1;if(n
){if(1==n){r=
x;}else{k t =
Power(x,n>>1)
;if(1&n){r=x;
}r *= t*t; }}
return r ;}

-- 
Richard Heathfield : binary@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton


Relevant Pages

  • Re: Recursive Functions
    ... > Power, and multiplying by x again if n was odd, and to find a ... > suitable base case to stop the recursion. ...
    (comp.lang.c)
  • Re: Recursive Functions
    ... > Power, and multiplying by x again if n was odd, and to find a ... > suitable base case to stop the recursion. ... Rewrite your word problem into a recurrence relationship. ...
    (comp.lang.c)
  • Re: Recursive Functions
    ... > Power, and multiplying by x again if n was odd, and to find a ... > suitable base case to stop the recursion. ...
    (comp.lang.c)
  • Re: Recursive Functions
    ... dmattis wrote: ... > Power, and multiplying by x again if n was odd, and to find a ... > suitable base case to stop the recursion. ...
    (comp.lang.c)
  • SF: Simpler derivation
    ... so multiplying the second by r^2, ... Notice here you can also see why j and M need to be odd, ... it does not, and you do a single pass and don't get a factorization, ... significant powers of 2. ...
    (sci.math)