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! 64 7326
On Mon, 27 Oct 2003 09:54:05 -0800, 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?
This question is off topic here. I would suggest you try
posting in comp.programmin g, but I can't actually figure out
what you want. You've described the algorithm completely,
what more do you want?
-Sheldon
p.s. I'm hoping that what you want isn't for someone to simply
do your homework for you.
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).
<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>
-- James
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?
This seems a fairly clear description of the procedure,
assuming `n' is a non-negative integer. (If `n' can be
negative the problem is harder; if `n' can be a non-integer
problem is much harder.) What problem are you having with
it? Perhaps if you'd show us what you've written thus far,
someone will be able to help.
-- Er*********@sun .com
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 : bi****@eton.pow ernet.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
"Sheldon Simms" <sh**********@y ahoo.com> wrote in message
news:pa******** *************** *****@yahoo.com ... On Mon, 27 Oct 2003 09:54:05 -0800, 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?
This question is off topic here. I would suggest you try posting in comp.programmin g, but I can't actually figure out what you want. You've described the algorithm completely, what more do you want?
Well, to help make it on topic, I sometimes notice C's lack of an integer
power function, such as that described. (Though I believe that it works
better as an iterative function than a recursive function.) Sometimes I use
an SQ macro, which squares an expression through mutliplication. If the
expression is more than a single variable, I hope that the compiler does
common subexpression elimination.
-- glen
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?
Thanks!
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.)
// Recursive raise integer to integer power
//
// If j is even, return (i^2)^(j/2), else return i * (i^2)^(j/2)
//
// ----------------------------------------------------
// (c) Copyright 2003 Julian V. Noble. //
// Permission is granted by the author to //
// use this software for any application pro- //
// vided this copyright notice is preserved. //
// ----------------------------------------------------
#include <math.h>
#include <stdio.h>
int power( int i, int j ); // prototype
int main( void )
{
int a;
int b;
printf("What are m and n? ");
scanf(" %d", &a);
scanf(" %d", &b);
printf( " %d\n", power(a,b) ) ;
return 0;
}
int power( int i, int j )
{
int k;
if (j==0) // i^0 = 1
{ return 1;
}
if (j & 1) // odd?
k = i;
else // even?
k = 1;
return k * power( i*i, j/2);
}
--
Julian V. Noble
Professor Emeritus of Physics jv*@spamfree.vi rginia.edu
^^^^^^^^ http://galileo.phys.virginia.edu/~jvn/
"Science knows only one commandment: contribute to science."
-- Bertolt Brecht, "Galileo".
Glen Herrmannsfeldt wrote: "Sheldon Simms" <sh**********@y ahoo.com> wrote in message news:pa******** *************** *****@yahoo.com ... On Mon, 27 Oct 2003 09:54:05 -0800, 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?
This question is off topic here. I would suggest you try posting in comp.programmin g, but I can't actually figure out what you want. You've described the algorithm completely, what more do you want?
Well, to help make it on topic, I sometimes notice C's lack of an integer power function, such as that described. (Though I believe that it works better as an iterative function than a recursive function.) Sometimes I use an SQ macro, which squares an expression through mutliplication. If the expression is more than a single variable, I hope that the compiler does common subexpression elimination.
-- glen
You are correct in saying that the iterative is probably better than the
recursive version. If anyone is interested I'll post my iterative version.
--
Julian V. Noble
Professor Emeritus of Physics jv*@spamfree.vi rginia.edu
^^^^^^^^ http://galileo.phys.virginia.edu/~jvn/
"Science knows only one commandment: contribute to science."
-- Bertolt Brecht, "Galileo".
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;
}
"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.
-- Er*********@sun .com This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
|
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
{
|
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.
|
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;
|
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.
| |
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
|
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!!!
|
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...
|
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():
|
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...
|
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...
| |
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,...
|
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...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |