Recursion function to find power of number - c++

I'm writing a recursion function to find the power of a number and it seems to be compiling but doesn't output anything.
#include <iostream>
using namespace std;
int stepem(int n, int k);
int main()
{
int x, y;
cin >> x >> y;
cout << stepem(x, y) << endl;
return 0;
}
int stepem(int n, int k)
{
if (n == 0)
return 1;
else if (n == 1)
return 1;
else
return n * stepem(n, k-1);
}
I tried debugging it, and it says the problem is on this line :
return n * stepem(n, k-1);
k seems to be getting some weird values, but I can't figure out why?

You should be checking the exponent k, not the number itself which never changes.
int rPow(int n, int k) {
if (k <= 0) return 1;
return n * rPow(n, --k);
}
Your k is getting weird values because you will keep computing until you run out of memory basically, you will create many stack frames with k going to "-infinity" (hypothetically).
That said, it is theoretically possible for the compiler to give you a warning that it will never terminate - in this particular scenario. However, it is naturally impossible to solve this in general (look up the Halting problem).

Your algorithm is wrong:
int stepem(int n, int k)
{
if (k == 0) // should be k, not n!
return 1;
else if (k == 1) // this condition is wrong
return 1;
else
return n * stepem(n, k-1);
}
If you call it with stepem(2, 3) (for example), you'll get 2 * 2 * 1 instead of 2 * 2 * 2 * 1. You don't need the else-if condition:
int stepem(int n, unsigned int k) // unless you want to deal with floating point numbers, make your power unsigned
{
if (k == 0)
return 1;
return n * stepem(n, k-1);
}

Didn't test it but I guess it should give you what you want and it is tail recursive.
int stepemi(int result, int i int k) {
if (k == 0 && result == i)
return 1;
else if (k == 0)
return result;
else
return stepem(result * i, i, k-1);
}
int stepem(int n, int k) {
return stepemi(n, n, k);
}
The big difference between this piece of code and the other example is that my version could get optimized for tail recursive calls. It means that when you call stepemi recursively, it doesn't have to keep anything in memory. As you can see, it could replace the variable in the current stack frame without having to create a new one. No variable as to remain in memory to compute the next recursion.
If you can have optimized tail recursive calls, it also means that the function will used a fixed amount of memory. It will never need more than 3 ints.
On the other hand, the code you wrote at first creates a tree of stackframe waiting to return. Each recursion will add up to the next one.

Well, just to post an answer according to my comment (seems I missed adding a comment and not a response :-D). I think, mainly, you have two errors: you're checking n instead of k and you're returning 1 when power is 1, instead of returning n. I think that stepem function should look like:
Edit: Updated to support negative exponents by #ZacHowland suggestion
float stepem(int n, int k)
{
if (k == 0)
return 1;
else
return (k<0) ?((float) 1/n) * stepem(n, k+1) :n * stepem(n, k-1);
}

// Power.cpp : Defines the entry point for the console application.
//
#include <stream>
using namespace std;
int power(int n, int k);
void main()
{
int x,y;
cin >>x>>y;
cout<<power(x,y)<<endl;
}
int power(int n, int k)
{
if (k==0)
return 1;
else if(k==1) // This condition is working :) //
return n;
else
return n*power(n,k-1);
}

your Program is wrong and it Does not support negative value given by user,
check this one
int power(int n, int k){
'if(k==0)
return 1;
else if(k<0)
return ((x*power(x,y+1))*(-1));
else
return n*power(n,k-1);
}

sorry i changed your variable names
but i hope you will understand;
#include <iostream>
using namespace std;
double power(double , int);// it should be double because you also need to handle negative powers which may cause fractions
int main()
{
cout<<"please enter the number to be powered up\n";
double number;
cin>>number;
cout<<"please enter the number to be powered up\n";
int pow;
cin>>pow;
double result = power(number, pow);
cout<<"answer is "<<result <<endl;
}
double power( double x, int n)
{
if (n==0)
return 1;
if (n>=1)
/*this will work OK even when n==1 no need to put additional condition as n==1
according to calculation it will show x as previous condition will force it to be x;
try to make pseudo code on your note book you will understand what i really mean*/
if (n<0)
return x*power(x, n-1);
return 1/x*power(x, n+1);// this will handle negative power as you should know how negative powers are handled in maths
}

int stepem(int n, int k)
{
if (k == 0) //not n cause you have to vary y i.e k if you want to find x^y
return 1;
else if (k == 1)
return n; //x^1=x,so when k=1 it should be x i.e n
else
return n * stepem(n, k-1);
}

Related

Finding greatest power devisor using recursion?

The question asks me to find the greatest power devisor of (number, d) I found that the function will be like that:
number % d^x ==0
I've done so far using for loop:
int gratestDevisor(int num, int d){
int p = 0;
for(int i=0; i<=num; i++){
//num % d^i ==0
if( (num % (int)pow(d,i))==0 )
p=i;
}
return p;
}
I've tried so much converting my code to recursion, I can't imagine how to do it and I'm totally confused with recursion. could you give me a tip please, I'm not asking you to solve it for me, just some tip on how to convert it to recursion would be fine.
Here is a simple method with recursion. If ddivides num, you simply have to add 1 to the count, and divide num by d.
#include <stdio.h>
int greatestDevisor(int num, int d){
if (num%d) return 0;
return 1 + greatestDevisor (num/d, d);
}
int main() {
int num = 48;
int d = 2;
int ans = greatestDevisor (num, d);
printf ("%d\n", ans);
return 0;
}
A recursive function consist of one (or more) base case(es) and one (or more) calls to the function itself. The key insight is that each recursive call reduces the problem to something smaller till the base case(es) are reached. State (like partial solutions) are either carried in arguments and return value.
You asked for a hint so I am explicitly not providing a solution. Others have.
Recursive version (which sucks):
int powerDividing(int x, int y)
{
if (x % y) return 0;
return 1 + powerDividing(x/y, y);
}

int limit in permutation program (C++)

I wrote a simple C++ program that computes permutations/factorials in 2 different methods. The problem arises when I try to use the longer method (p1) with 20 and 2. Granted, "20!" is a HUGE number. Is there a limit with integers when calculating the factorial using the recursion method?
#include <iostream>
using namespace std;
int p1(int n, int r);
int p2(int n, int r);
int factorial(int x);
int main()
{
cout << p1(10, 8) << endl;
cout << p2(10, 8) << endl;
cout << p1(4, 3) << endl;
cout << p2(4, 3) << endl;
cout << p1(20, 2) << endl; // THE NUMBER PRINTS INCORRECTLY HERE
cout << p2(20, 2) << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
int p1(int n, int r) // long version, recursively calls factorial
{
return (factorial(n) / factorial(n - r));
}
int factorial(int x)
{
if (x == 0)
return 1;
else if (x > 0)
return (x * factorial(x - 1));
}
int p2(int n, int r) // shortcut, does arithmetic in for loop
{
int answer = n;
for (int i = 1; i < r; i++)
{
answer *= n - 1;
n--;
}
return answer;
}
20! is 2.4*10^18
You can check out a reference of limits.h to see what the limits are.
consider that 2^32 is 4.2*10^9. long int is usually a 32-bit value.
consider that 2^64 is 1.8*10^19, so a 64-bit integer will get you through 20! but no more. unsigned long long int should do it for you then.
unsigned long long int p1(int n, int r)
{
return (factorial(n) / factorial(n - r));
}
unsigned long long int factorial(unsigned long long int x)
{
if (x == 0)
return 1;
else if (x > 0)
return (x * factorial(x - 1));
}
unsigned long long int p2(int n, int r)
{
unsigned long long int answer = n;
for (int i = 1; i < r; i++)
{
answer *= n - 1;
n--;
}
return answer;
}
If you are allowed in this assignment, consider using float or double, unless you need absolute precision, or just need to get to 20 and be done. If you do need absolute precision and to perform a factorial above 20, you will have to devise a way to store a larger integer in a byte array like #z32a7ul states.
Also you can save an operation by doing answer *= --n; to pre-decrement n before you use it.
20! exceeds the integer range. Your shortcut function doesn't exceed simply because you don't calculate the whole faculty, but 20*19
If you really need it, you may create a class that holds a variable-length array of bytes, and define operators on it. In that case, only the available memory and your patiance will limit the size of numbers. I think Scheme (a LISP dialect) does something like that.

Multiplying a digit of a number with its current position and then add it with the others using recursion

the point of this exercise is to multiply a digit of a number with its current position and then add it with the others. Example: 1234 = 1x4 + 2x3 + 3x2 + 4x1 .I did this code successfully using 2 parameters and now i'm trying to do it with 1. My idea was to use - return num + mult(a/10) * (a%10) and get the answer, , because from return num + mult(a/10) i get the values 1,2,3,4- (1 is for mult(1), 2 for mult(12), etc.) for num, but i noticed that this is only correct for mult(1) and then the recursion gets wrong values for mult(12), mult(123), mult(1234). My idea is to independently multiply the values from 'num' with a%10 . Sorry if i can't explain myself that well, but i'm still really new to programming.
#include <iostream>
using namespace std;
int mult(int a){
int num = 1;
if (a==0){
return 1;
}
return ((num + mult(a/10)) * (a%10));
}
int main()
{
int a = 1234;
cout << mult(a);
return 0;
}
I find this easier and more logically to do, Hope this helps lad.
int k=1;
int a=1234;
int sum=0;
while(a>0){
sum=sum+k*(a%10);
a=a/10;
k++;
}
If the goal is to do it with recursion and only one argument, you may achieve it with two functions. This is not optimal in terms of number of operations performed, though. Also, it's more of a math exercise than a programming one:
#include <iostream>
using namespace std;
int mult1(int a) {
if(a == 0) return 0;
return a % 10 + mult1(a / 10);
}
int mult(int a) {
if(a == 0) return 0;
return mult1(a) + mult(a / 10);
}
int main() {
int a = 1234;
cout << mult(a) << '\n';
return 0;
}

Undoing a recursion tree

SHORT How should I reduce (optimize) the number of needed operations in my code?
LONGER For research, I programmed a set of a equations in C++ to output a sequence if it fits the model. On the very inside of the code is this function, called MANY times during run-time:
int Weight(int i, int q, int d){
int j, sum = 0;
if (i <= 0)
return 0;
else if (i == 1)
return 1;
for (j = 1; j <= d; j++){
sum += Weight((i - j), q, d);
}
sum = 1 + ((q - 1) * sum);
return sum;
}
So based on the size of variable d, the size of the index i, and how many times this function is called in the rest of the code, many redundant calculations are done. How should I go about reducing the number of calculations?
Ideally, for example, after Weight(5, 3, 1) is calculated, how would I tell the computer to substitute in its value rather than recalculate its value when I call for Weight(6, 3, 1), given that the function is defined recursively?
Would multidimensional vectors work in this case to store the values? Should I just print the values to a file to be read off? I have yet to encounter an overflow with the input sizes I'm giving it, but would a tail-recursion help optimize it?
Note: I am still learning how to program, and I'm amazed I was even able to get the model right in the first place.
You may use memoization
int WeightImpl(int i, int q, int d); // forward declaration
// Use memoization and use `WeightImpl` for the real computation
int Weight(int i, int q, int d){
static std::map<std::tuple<int, int, int>, int> memo;
auto it = memo.find(std::make_tuple(i, q, d));
if (it != memo.end()) {
return it->second;
}
const int res = WeightImpl(i, q, d);
memo[std::make_tuple(i, q, d)] = res;
return res;
}
// Do the real computation
int WeightImpl(int i, int q, int d){
int j, sum = 0;
if (i <= 0)
return 0;
else if (i == 1)
return 1;
for (j = 1; j <= d; j++){
sum += Weight((i - j), q, d); // Call the memoize version to save intermediate result
}
sum = 1 + ((q - 1) * sum);
return sum;
}
Live Demo
Note: As you use recursive call, you have to be cautious with which version to call to really memoize each intermediate computation. I mean that the recursive function should be modified to not call itself but the memoize version of the function. For non-recursive function, memoization can be done without modification of the real function.
You could use an array to store the intermediate values. For example, for certain d and q have an array that contains the value of Weight(i, q, d) at index i.
If you initialize the array items at -1 you can then do in your function for example
if(sum_array[i] != -1){ // if the value is pre-calculated
sum += sum_array[i];
}
else{
sum += Weight((i - j), q, d);
}

C++ function to preform division

Im trying to make a function that does division with out the / symbol
long q(int nm1, int nm2)
{
long q = 0;
while ( num1 > num2)
{
some subtraction here
}
return q;
}
the idea is to assume the input is in order and the first is to be divided by the second.
This means subtract the second from the first until the second is less then the first number.
I tried many different ways to do this but for what ever reason I cant hit it.
For now I am assuming the number is positive and wont return division by zero (I can fix that later by calling my other functions)
This means subtract the the second from the first until the second is less than the first number.
And what's the problem with that?
int div(int num, int den)
{
int frac;
for (frac = 0; num >= den; num -= den, frac++)
;
return frac;
}
What you're original post is trying to do is the Division by repeated subtraction algorithm. Have a look at Wikipedia:
The simplest division algorithm, historically incorporated into a
greatest common divisor algorithm presented in Euclid's Elements, Book
VII, Proposition 1, finds the remainder given two positive integers
using only subtractions and comparisons
while N ≥ D do
N := N - D
end
return N
Just add a counter in your while loop to keep track of the number of iterations (which is what you will want to return) and after your loop N will contain your remainder (if it is not 0 of course).
This code will work only if the num and den are integer values.
int main( int num, int den )
{
if(den==0)
{
return 1;
}
else
{
while(num!=0)
{
num = num - den;
}
}
return 0;
}
Just improving the above answer slightly.
Use modulus
long div(int num, int den)
{
int frac;
int num2 = num;
for (frac = 0; num2 >= den; num2 -= den, frac++)
;
// i needed the original num and den.
return ( (long) frac )+( num % den );
// casts frac to long then adds the modulus remainder of the values.
}
just a bit optimization: you don't want to have linear time complexity with the input value
int div(int num, int den)
{
int result = 0;
int i;
long long x;
long long y;
if (num < 0) return -div(-num, den);
if (den < 0) return -div(num, den);
if (num < den) return 0;
x = num;
y = den;
i = 0;
while((i < 32) && (x > (y << (i+1)))) i++;
for(;i>0; i++)
{
if (x > (y << i))
{
x -= y;
result += 1 << i;
}
}
return result;
}