I wrote the code but I am getting the wrong output. Say for example when I enter 5 the output I am getting is 3 instead it should be -5. Please point out my mistakes and provide me some solutions.
#include <stdio.h>
int difference(int a);
int difference(int a)
{
if (a != 0)
{
return (a - difference(a - 1));
}
else
{
return 0;
}
}
int main()
{
int n;
printf("Enter number until which you want difference of:\n");
scanf("%d", &n);
printf("The difference of numbers is %d", difference(n));
return 0;
}
>Solution :
As this seems home work, just the error cause:
d 5 = [a] 5 - d 4 = [k] 5 - 2 = 3
d 4 = [b] 4 - d 3 = [j] 4 - 2
d 3 = [c] 3 - d 2 = [i] 3 - 1
d 2 = [d] 2 - d 1 = [h] 2 - 1
d 1 = [e] 1 - d 0 = [g] 1 - 0
d 0 = [f] 0
Bad algorithm, bad, bad.
If difference between two numbers is meant:
int difference(int a, int b)
{
if (a == b)
{
return 0;
}
else if (a > b)
{
return 1 + difference(a - 1, b);
}
else //if (a < b)
{
return difference(b, a);
}
}
Even if this is home work, a solution:
int identityByRecursiveDifference(int a)
{
return a == 0 ? 0 : 1 + identityByRecursiveDifference(a - 1);
}
Here the difference is 1.
int identityByRecursiveDifference(int a)
{
if a == 0 {
return 0;
}
int half = identityByRecursiveDifference(a / 2);
return 2 * half + (a % 2);
}
Here the difference is half; exact with even a or about with odd a.
a % 2 is remainder by division of 2.
Less recursion, not a steps but ²log a steps.