Recurrence Functions

I am working on this program for an assignment and I cant figure out how to get it to work. I am not asking to do my homework just assistance. I have some to find a number odd or even and then put it through a recurrence relation.

.........{ 0 if n=0
f(n)= { f(1/2n) if n is even, n > 0
.........{1+f(n-1) if n is odd, n > 0

So what i figured was that i can find if the number that the user entered is odd or even by running it through a function and then put that number through the even or odd function. When i run the program i just get 0,0 for any number. I know something isnt right but i cant just find it.

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <cmath>

using namespace std;

bool isOdd(int integer)
{
  if ( integer % 2== 0 )
     return true;
  else
     return false;
}

int EvenOdd (int integer)
{	
int integerOdd;
int integerEven;

     if(isOdd(integer) == true)
        return integerOdd;
     else
		return integerEven;
}

int Even(int integer)
{
	if(integer = 0)
		return 0;
	else if(integer > 0)
		return (Even(integer * (1/2)));

}
int Odd(int integer)
{
	if(integer = 0)
		return 0;
	else if(integer > 0)
		return (1 + (Odd(integer-1)));
}

int main (int argc, char *argv[])
{
	double factorialOdd;
	double factorialEven;
	double EvenOrOdd;
	double OddEven;
	double num;
	
	cout << "What number do you want to factorial?: ";
	cin >> num;
	
	OddEven = isOdd(num);
	EvenOrOdd = EvenOdd(OddEven);
	factorialEven = Even(EvenOrOdd);
	factorialOdd = Odd(EvenOrOdd);
	
	cout << factorialEven << endl;
	cout << factorialOdd << endl;
	
	return 0;
}


Thanks for you guys help.
Last edited on
If a number n is odd then n % 2 != 0 So your function isOdd is semantically incorrect. It shall look as

1
2
3
4
inline bool isOdd( int integer )
{
   return ( integer % 2 != 0 );
}


It is not clear whether function Odd shall calculate the sum of kind 1 + 1 +...+ 1 or n + n-1 + n-2+...+1. In any case your function is incorrect because instead of the comparision operator == you use the assignment operator
=

1
2
3
4
5
6
7
int Odd(int integer)
{
	if(integer = 0)
		return 0;
	else if(integer > 0)
		return (1 + (Odd(integer-1)));
}


Shall be

1
2
3
4
5
6
7
int Odd(int integer)
{
	if( integer == 0 )
		return 0;
	else if ( integer > 0 )
		return ( 1 + Odd( integer -1 ) ) ;
}


Try to update the rest by youself.
Topic archived. No new replies allowed.