473,787 Members | 2,971 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

power using recursion

17 New Member
the question is to calculate x^n(x power n) (whr n can be +ve or -ve) by using recursion. the algorithm is
x= 1, n=0
1/x^n, n<0
x*x^(n-1), n>0


ive written the program it runs but im not having the correct values..here is the code:

Expand|Select|Wrap|Line Numbers
  1. #include<iostream.h>
  2. #include<conio.h>
  3.  
  4. int power(int n);
  5. int x,n;
  6. void main()
  7. {clrscr();
  8. cout<<"Input a value for x"<<endl;
  9. cin>>x;
  10. cout<<"\n Input a value for n"<<endl;
  11. cin>>n;
  12. cout<<"The final answer is"<<power(n);
  13. getch();
  14. }
  15.  
  16. int power(int n)
  17. { if (n==0)
  18.       return 1;
  19.   else if (n<0)
  20.       return (1/(x*power(n)));
  21.   else
  22.       return (x*(x*power(n-1)));
  23. }


i knw the problem comes frm the foll part
else if (n<0)
return (1/(x*power(n)));
else
return (x*(x*power(n-1)));

i shud not multiply x by power() but thn hw do i do it??? if i dont multiply i just put it like that

else if (n<0)
return (1/(x power(n)));
else
return (x*(x power(n-1)));


i get error!!

plzzz help
Feb 17 '07 #1
3 6964
horace1
1,510 Recognized Expert Top Contributor
should you equation for x^n be
Expand|Select|Wrap|Line Numbers
  1.       return (x*power(n-1));
  2.  
Feb 17 '07 #2
Ganon11
3,652 Recognized Expert Specialist
the algorithm is
x= 1, n=0
1/x^n, n<0
x*x^(n-1), n>0

Expand|Select|Wrap|Line Numbers
  1. int power(int n)
  2.   if (n==0)
  3.       return 1;
  4.   else if (n<0)
  5.       return (1/(x*power(n)));
  6.   else
  7.       return (x*(x*power(n-1)));
  8. }
The problem appears to be in your second branch. If n < 0, you will indeed call the recursive function again, but you are passing it the same value of n. This value is negative still, and so you will always execute the second branch. Thus, n never changes, and your end condition is never reached. While you coded your given algorithm correctly, the algorithm itself is wrong. Try this algorithm:

x^n = 1 / (x ^ |n|), where n < 0 and |n| is the absolute value of n.

Also, your third branch (for n > 0) multiplies the value by an extra x. It should just be x * power(n-1).

Next I'd suggest passing power the x value as well, rather than having both values declared as global. This will make the function portable, so you will not have to rewrite a recursive power function ever time you need one.

Finally, 1 / anything will be a double value, but your function returns an integer. This means that any negative exponent created will be returned as x. You should make this function return a double.
Feb 17 '07 #3
AdrianH
1,251 Recognized Expert Top Contributor
Expand|Select|Wrap|Line Numbers
  1. int power(int n)
  2. { if (n==0)
  3.       return 1;
  4.   else if (n<0)
  5.       return (1/(x*power(n)));
  6.   else
  7.       return (x*(x*power(n-1)));
  8. }
Ganon11 forgot to mention that your second branch should be returning x*(1/power(n+1)).

Adrian

P.S. As Ganon11 stated, You really shouldn't be using global variables Get power to take a param double x. And move the n inside of the main(). Using global variables is a very bad form to get used to and it will bite you in the ass later.
Feb 17 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

5
3349
by: hokiegal99 | last post by:
A few questions about the following code. How would I "wrap" this in a function, and do I need to? Also, how can I make the code smart enough to realize that when a file has 2 or more bad charcters in it, that the code needs to run until all bad characters are gone? For example, if a file has the name "<bad*mac\file" the program has to run 3 times to get all three bad chars out of the file name. The passes look like this:
12
2768
by: da Vinci | last post by:
Greetings. I want to get everyone's opinion on the use of recursion. We covered it in class tonight and I want a good solid answer from people in the "know" on how well recursion is accepted in modern day applications. Should we readily use it when we can or only when absolutly forced to use it?
6
4018
by: Stephane Belzile | last post by:
Is there a way I can detect in vb.Net the power has switched to a UPS unit in case of power failure? Thanks
12
2847
by: Roman Töngi | last post by:
I just want to raise a number to a power. e.g.: 16^2 The pow()-function of cmath seems to be not enough. I've read about valarray. Is it really so difficult? Can you give me an example. Thanks Roman
75
5644
by: Sathyaish | last post by:
Can every problem that has an iterative solution also be expressed in terms of a recursive solution? I tried one example, and am in the process of trying out more examples, increasing their complexity as I go. Here's a simple one I tried out: #include<stdio.h> /* To compare the the time and space cost of iteration against
18
3724
by: MTD | last post by:
Hello all, I've been messing about for fun creating a trial division factorizing function and I'm naturally interested in optimising it as much as possible. I've been told that iteration in python is generally more time-efficient than recursion. Is that true? Here is my algorithm as it stands. Any suggestions appreciated!
5
6450
by: mathon | last post by:
hi, i develeoped a recursive function for the power and it works fine double power(double x, int n) { if (n < 0) return 1/power(x, -n); else if (n == 0) return 1.0;
9
1794
by: mathon | last post by:
hi, i already posted an entry because of this problem, unfortunately i havent solved it so far..:( I have created a recursion for the calculation of the power like this: double power(double x, int n) {
35
4741
by: Muzammil | last post by:
int harmonic(int n) { if (n=1) { return 1; } else { return harmonic(n-1)+1/n; } } can any help me ??
0
9655
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
10363
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
10169
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...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8993
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...
0
6749
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();...
0
5398
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
4067
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
3670
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.