Rewriting a recursive function to a non-recursive function - c++

int foo(int x)
{
if (x >= 0)
{
return (x - 1) + 2 * foo(x - 1);
}
else
{
return 1;
}
}
Hi, I need to rewrite this function such that it will be free of recursion. I tried solving this mathematically, but to no avail. I am new to programming, so any help will be much appreciated. Thanks in advance!

I assume that it really should be if(x>0) in your question.
Then examining your function, we see that foo(0)=1 and otherwise that foo(x)=(x-1)+2*foo(x-1). Thus foo(x) only depends on foo(x-1). So, you can simply use an iteration to progress the result
int foo(int x)
{
auto result=1; // result if x=0
for(int n=0; n!=x; ++n) // increment result to desired x
result=n+2*result; // corresponds to (x-1)+2*foo(x-1) in original
return result;
}
If it really was if(x>=0) instead, I leave it as an exercise to you to adapt the code.

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);
}

Recursive call getting stuck

#include <bits/stdc++.h>
using namespace std;
int gcd(long long int a, long long int b){
if(a||b==0){
return 0;
}
else if(b==a){
return a;
}
else if(a>b){
return gcd(a-b,b);
}
else{
return gcd(a,b-a);
}
}
int lcm(long long int a,long long int b){
return a*b/(gcd(a,b));
}
int main(){
long long int answer=1;
for (int i = 2; i<=20; i++) {
answer=lcm(i,answer);
cout<<answer;
}
cout<<answer;
return 0;
}
i wrote this code for problem 5 in project euler. however the output screen is showing nothing and is getting hanged. i put a few debugging cout statements and i understood that in the main function the it is entering the loop but it is not continuing the excution after the call for lcm.
the program is to find the lcm of numbers from 1 to 20. i used the formula llcm= a*b/gcd(a,b). where in gcd also i used the recursive euclidian algorithm. i am not able to trace out the reason for this bug . could anyone help pls.
also if there any suggestions regarding my coding style (indentation, type casting, variable names, algorithm or anything) please point it out. i am beginner so i do not know much regarding c++ and programming styles.
Your program is becoming stuck because of this line:
if (a || b == 0) {
The == operator has higher precedence than ||, so the condition is in fact the same as:
if (a || (b == 0)) {
Which in C(++) is the same as:
if ((a != 0) || (b == 0)) {
That is, if a is non-zero OR b is zero. a will be non-zero straight away, hence your program will always try to divide by zero, which causes problems. I am not sure where you found this version of the algorithm, a cursory search results in a much simpler variant:
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, (a % b));
}
}
As for the second part of your question, there are many little (stylistic) issues in your code that I would change. Inconsistent spacing, unnecessary use of long long int (an int would do just fine here) … But for these, I recommend the codereview StackExchange.

Call recursive function in std::function

I just wrote a thread pool using C++11/14 std::thread objects and use tasks in the worker queue. I encountered some weird behaviour when calling recursive functions in lambda expressions. The following code crashes if you implement fac() in a recursive fashion (both with clang 3.5 and gcc 4.9):
#include <functional>
#include <vector>
std::size_t fac(std::size_t x) {
// This will crash (segfault).
// if (x == 1) return 1;
// else return fac(x-1)*x;
// This, however, works fine.
auto res = 1;
for (auto i = 2; i < x; ++i) {
res *= x;
}
return res;
}
int main() {
std::vector<std::function<void()> > functions;
for (auto i = 0; i < 10; ++i) {
functions.emplace_back([i]() { fac(i); });
}
for (auto& fn : functions) {
fn();
}
return 0;
}
It does, however, work fine with the iterative version above. What am I missing?
for (auto i = 0; i < 10; ++i) {
functions.emplace_back([i]() { fac(i); });
The first time through that loop, i is going to be set to zero, so you're executing:
fac(0);
Doing so with the recursive definition:
if (x == 1) return 1;
else return fac(x-1)*x;
means that the else block will execute, and hence x will wrap around to whatever the maximum size_t value is (as it's unsigned).
Then it's going to run from there down to 1, consuming one stack frame each time. At a minimum, that's going to consume 65,000 or so stack frames (based on the minimum allowed value of size_t from the standards), but probably more, much more.
That's what causing your crash. The fix is relatively simple. Since 0! is defined as 1, you can simply change your statement to be:
if (x <= 1)
return 1;
return fac (x-1) * x;
But you should keep in mind that recursive functions are best suited to those cases where the solution space reduces quickly, a classic example being the binary search, where the solution space is halved every time you recur.
Functions that don't reduce solution space quickly are usually prone to stack overflow problems (unless the optimiser can optimise away the recursion). You may still run into problems if you pass in a big enough number and it's no real different to adding together two unsigned numbers with the bizarre (though I actually saw it put forward as a recursive example many moons ago):
def addu (unsigned a, b):
if b == 0:
return a
return addu (a + 1, b - 1)
So, in your case, I'd stick with the iterative solution, albeit making it bug-free:
auto res = 1;
for (auto i = 2; i <= x; ++i) // include the limit with <=.
res *= i; // multiply by i, not x.
Both definitions have different behavior for x=0. The loop will be fine as it uses the less-than operator:
auto res = 1;
for (auto i = 2; i < x; ++i) {
res *= x;
}
However,
if (x == 1) return 1;
else return fac(x-1)*x;
Results in a quasi-infinite loop as x == 1 is false and x-1 yields the largest possible value of std::size_t (typically 264-1).
The recursive version does not take care of the case for x == 0.
You need:
std::size_t fac(std::size_t x) {
if (x == 1 || x == 0 ) return 1;
return fac(x-1)*x;
}
or
std::size_t fac(std::size_t x) {
if (x == 0 ) return 1;
return fac(x-1)*x;
}

Recursion function to find power of number

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);
}

GCD function in c++ sans cmath library

I'm writing a mixed numeral class and need a quick and easy 'greatest common divisor' function. Can anyone give me the code or a link to the code?
The libstdc++ algorithm library has a hidden gcd function (I'm using g++ 4.6.3).
#include <iostream>
#include <algorithm>
int main()
{
std::cout << std::__gcd(100,24); // print 4
return 0;
}
You are welcome :)
UPDATE: As #chema989 noted it, in C++17 there is std::gcd() function available with <numeric> header.
I'm tempted to vote to close -- it seems difficult to believe that an implementation would be hard to find, but who knows for sure.
template <typename Number>
Number GCD(Number u, Number v) {
while (v != 0) {
Number r = u % v;
u = v;
v = r;
}
return u;
}
In C++ 17 or newer, you can just #include <numeric>, and use std::gcd (and if you care about the gcd, chances are pretty fair that you'll be interested in the std::lcm that was added as well).
A quick recursive version:
unsigned int gcd (unsigned int n1, unsigned int n2) {
return (n2 == 0) ? n1 : gcd (n2, n1 % n2);
}
or the equivalent iterative version if you're violently opposed to recursion (a):
unsigned int gcd (unsigned int n1, unsigned int n2) {
unsigned int tmp;
while (n2 != 0) {
tmp = n1;
n1 = n2;
n2 = tmp % n2;
}
return n1;
}
Just substitute in your own data type, zero comparison, assignment and modulus method (if you're using some non-basic type like a bignum class, for example).
This function actually came from an earlier answer of mine for working out integral aspect ratios for screen sizes but the original source was the Euclidean algorithm I learnt a long time ago, detailed here on Wikipedia if you want to know the math behind it.
(a) The problem with some recursive solutions is that they approach the answer so slowly you tend to run out of stack space before you get there, such as with the very badly thought out (pseudo-code):
def sum (a:unsigned, b:unsigned):
if b == 0: return a
return sum (a + 1, b - 1)
You'll find that very expensive on something like sum (1, 1000000000) as you (try to) use up a billion or so stack frames. The ideal use case for recursion is something like a binary search where you reduce the solution space by half for each iteration. The greatest common divisor is also one where the solution space reduces rapidly so fears about massive stack use are unfounded there.
For C++17 you can use std::gcd defined in header <numeric>:
auto res = std::gcd(10, 20);
The Euclidean algorithm is quite easy to write in C.
int gcd(int a, int b) {
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}