Divide by recursion

Feb 21, 2017 at 5:20pm
Hello, this program should divide n/(n-1) using recursion. I need it to work like - if i do input = 6 it have to 6/5/4/3/2/1 and output = 0.05, but it does something like this 6/5*4/3*2/1 and output of this program is 3.2. I wonder what am i doing wrong.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  #include "stdafx.h"
#include <iostream>
using namespace std;

double Defactorial(double n);

int main()
{
		double n;
		cout << "Enter n: ";
		cin >> n;
	if(n <= 1)
	{
		cout << "n should be higher than 3 !" << endl;
	}
	if (n >= 2)
	{
		cout << "The result is " << Defactorial(n)<<endl;
	}
    return 0;
}

double Defactorial(double n)
{
	if (n >= 1)
	{
		cout << n << endl;
		return n / Defactorial(n - 1);
	}
	else
	{
		return 1;
	}
}
Last edited on Feb 21, 2017 at 5:25pm
Feb 21, 2017 at 5:47pm
It seems to me that you're really computing n/(n-1)!. As such, I'd just code up a factorial funciton. Then line 18 would be cout << "The result is " << static_cast<double>(n) / factorial(n-1)<<endl;

Also, when coding a recursive function, we tend to think about the recursion and forget the base case. For that reason, I always write recursive functions using the pattern:
1
2
3
4
5
if (base case) {
    return the base case;
} else {
    do the recursion
}
Last edited on Feb 21, 2017 at 5:49pm
Feb 21, 2017 at 6:19pm
if i do input = 6 it have to 6/5/4/3/2/1
-->This also does not seem to be what you really want.

You want n/( (n - 1)! ) where (6 - 1)! = 5 * 4 * 3 * 2 * 1

So instead of making the entire thing recursive, break it up. Make the factorial part recursive and divide the original function by the factorial.


Otherwise you could input a sentry variable, something to say that the defactorial function has been called by the user instead of by itself. That will give you a way to stop the factorial portion and divide the original input...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
double defactorial(double start, bool sentry)
{
    if(sentry)
    {
        return start/defactorial(start - 1, false);
    }
    else if(start > 1)
    {
        return start * defactorial(start - 1, false);
    }
    else
    {
        return 1;
    }
}


I haven't tested the above, but it shows the basic idea, only the user is allowed to enter true as the sentry value. (If the user inputs false it looks like they would get factorial instead which actually works on a grammatical level. Double-Negative)
Last edited on Feb 21, 2017 at 6:42pm
Topic archived. No new replies allowed.