Recursive function divide a number - c

I need to create a recursive function that receives a number by two without using /.
This is what I wrote, but it works only if after dividing it will still be a decimal number and not a float, that's why I asked.
int recursive(int a, int b){
if ( a == (0.5 * b) )
return a;
return recursive(a-1, b);
}
Btw, the function can receive only 1 parameter not 2 or more :/

I think you need something like this
int divide(int a, int b){
if(a - b <= 0){
return 1;
}
else {
return divide(a - b, b) + 1;
}
}

This divides by two using repeated subtraction and recursion.
int divide_by_two(int a) {
if (a < 0) return -divide_by_two(-a);
if (a < 2) return 0;
return 1 + divide_by_two(a - 2);
}
Generalising, this divides a by b using repeated subtraction and recursion.
int divide(int a, int b) {
if (a < 0) return -divide(-a, b);
if (b < 0) return -divide(a, -b);
if (a < b) return 0;
return 1 + divide(a - b, b);
}
Note, these functions don't round exactly the same way that division is defined to do in C.

You can try this, it should work:
int dividebytwo (int a){
static int answer = 0;
if (a < 0){
if ((answer * 2) > a){
answer --;
return dividebytwo (a);
}
return answer;
} else if (a > 0){
if ((answer * 2) < a){
answer ++;
return dividebytwo (a);
}
return answer;
}
return 0;
}
The trick here is using the static attribute. The static attribute means that the variable is only initialized once and retains its value after every function call. Really, you're using two parameters but it looks like you're only using one.
The only downside to this function is that you can only count on it to work more than once. Since this is probably for a simple homework assignment, it probably doesn't matter. But in reality, this is considered hugely inefficient and unreliable.
To compensate for the only-works-once factor, may add one of these fixes:
declare answer as a global variable and set it to 0 before every function call.
append return answer = 0; to the end of the function, instead of return 0;. This is so that whenever you want to call it again, you would call it beforehand as dividebytwo (0);.
I also cannot stress enough how weird of a concept this is, it sets of all sorts of red flags for anyone who practices careful programming - could be why you're getting so many downvotes. So use with caution!

#include<stdio.h>
int divide(int a, int b){
if( a-b < 0)
return 0;
else if ( a-b == 0)
return 1;
else {
return divide(a-b, b) + 1;
}
}
http://codepad.org/o4CoiaON

Related

Is there a better way to exit all recursive functions at once, rather than one by one?

Is there a better way to exit all of the recursive iterations immediately after the if(a == b) condition is met, instead of having to include lines 7 and 8 in their current form? Without lines 7 and 8 as they currently are, it seems to exit merely the last iteration.
bool recursive(int a, int b) {
if(a == b)
return true;
for(int i = 0; i < count; i++)
if(locked[b][i] == true)
if(recursive(a, i) == true)
return true;
return false;
}
It's not really critical, but I'd like to spare lines whenever possible. Any ideas?
I would probably write this like so:
bool recursive(int a, int b) {
bool result = (a == b);
for (int i = 0; i < count && !result; i++) {
result = (locked[b][i] && recursive(a, i));
}
return result;
}
Introduction of a variable to hold the working result of the function allows for testing that result as part of the condition for performing a loop iteration. That way you can terminate the loop as soon as the result flips from false to true, yet you don't need any code to distinguish after the fact between the two possible reasons for loop termination.
Yes. You could use a bit obscure functionality of C named longjmp.
It allows to jump back a stack over multiple function calls. A bit similar to throw in C++.
Firstly, return environment is created with setjmp().
It returns 0 if to was a first call to setjmp().
Otherwise it returns a value set by longjmp() called deeper in the recursive call.
#include <stdio.h>
#include <setjmp.h>
void slowrec(int n) {
if (n == 0) {
puts("done");
} else {
puts("go down");
slowrec(n - 1);
puts("go up");
}
}
jmp_buf env;
void fastrec(int n) {
if (n == 0) {
puts("done");
longjmp(env, 1);
} else {
puts("go down");
fastrec(n - 1);
puts("go up");
}
}
int main() {
puts("-- slow recursion --");
slowrec(5);
puts("-- longjmp recursion --");
if (setjmp(env) == 0) {
fastrec(5);
}
return 0;
}
produces:
-- slow recursion --
go down
go down
go down
go down
go down
done
go up
go up
go up
go up
go up
-- longjmp recursion --
go down
go down
go down
go down
go down
done
For original problem the code may look like this:
jmp_buf env;
void recursive_internal(int a, int b) {
if (a == b) longjmp(env, 1); // true
for(int i = 0; i < count; i++)
if(locked[b][i])
recursive_internal(a, i);
}
bool recursive(int a, int b) {
if (setjmp(env) == 0) {
recursive_internal(a, b);
// left without triggering long jump
return false;
}
// returned with longjmp
return true;
}
Note that there is no return value in recursive_internal because either a==b condition is met and longjmp was taken as it was the only way true could be returned. Otherwise, condition was never met and the algorithm exited via return false.

Implementation of a double factorial tail-recursive function in C

I got stuck trying to implement the following formula in my C code:
N!! = N!/(N-1)!!
The code is supposed to be a tail-recursive function, and although it does work and the computation is correct, I'm pretty sure this is not a tail function + I really can't tell what's going on during the return stage.
My current code:
long long int Factorial(int n)
{
if (n < 0)
return 0;
if (n == 0 || n == 1)
return 1;
return (n*Factorial(n - 1));
}
int DoubleFactorialTail(int n, int fact)
{
if (n < 0)
{
return 0;
}
if (n == 0 || n == 1)
{
return fact;
}
else
{
long long int factorial = Factorial(n);
return (factorial / DoubleFactorialTail(n - 1, fact));
}
}
I know that a double factorial tail-recursive function is supposed to call the recursive function at the end and nothing else, but here what I did was divide it by value(recursive in this case), that's why I'm not so sure my implementation is correct.
EDIT:
I originally tried implementing the following:
long long int DoubleFactorialTail(int n, int fact)
{
if (n < 0)
{
return 1;
}
if (n == 0 || n == 1)
{
return fact;
}
else
{
return (DoubleFactorialTail(n - 2, fact*n));
}
}
and the result will be:
res = (Factorial(n)/DoubleFactorialTail(n-1, 1));
Thing is, we were told that for n<0, the function needs to return 0 and save it in res.
but this equation will have 0 in its denominator if I choose to proceed and implement it this way.
So I guess my main question is: Is there a way to write this code in a tail-recursion manner while keeping this criterion intact?
I know that a double factorial tail-recursive function is supposed to call the recursive function at the end and nothing else
This is true, so
return (n*Factorial(n - 1));
or
return (factorial / DoubleFactorialTail(n - 1, fact));
Is not going to work.
The pattern has to be literally
return CallToRecursive(args);
The reason is that a tail recursive optimization lets CallToRecursive(args); return to the caller of this function and does not add a frame to the call-stack.
If you add code that needs to further process the return value, then it needs a frame in the call-stack to hold the return value and return point, and that's not TCO.
The way to approach this is usually to pass along work in progress to the next call.
long long int FactorialTCO(int n, long long factSoFar)
{
if (n < 0)
return 0;
if (n == 0 || n == 1)
return factSoFar;
return FactorialTCO(n - 1, n * factSoFar);
}
long long int Factorial(int n) {
return FactorialTCO(n, 1);
}
Note that this line:
return FactorialTCO(n - 1, n * factSoFar);
Returns exactly what it gets back from the recursive call. This means the compiler does not need to make a new stack frame, and that call will return to this function's caller. As we do this multiple times, we can effectively jump all the way back to the first caller when we are done instead of unwinding the stack frame.
I leave the transformation of the double up to you or others.

Search of an element on a unsorted array recursively

This is an exercise that I took from an exam. It asks to write a function that receives an unsorted array v[] and a number X and the function will return 1 if X is present in v[] or 0 if X is not present in v[]. The function must be recursive and must work in this manner:
1. Compares X with the element in the middle of v[];
2. The function calls itself (recursion!!) on upper half and on the lower half of v[];
So I've written this function:
int occ(int *p,int dim,int X){
int pivot,a,b;
pivot=(dim)/2;
if(dim==0) //end of array
return 0;
if(*(p+pivot)==X) //verify if the element in the middle is X
return 1;
a=occ(p,pivot,X); //call on lower half
b=occ(p+pivot,dim-pivot,X); //call on upper half
if(a+b>=1) //if X is found return 1 else 0
return 1;
else{
return 0;
}
}
I tried to simulated it on a sheet of paper and it seems to be correct (Even though I'm not sure) then I've written it on ideone and it can't run the program!
Here is the link: https://ideone.com/ZwwpAW
Is my code actually wrong (probably!) or is it a problem related to ideone. Can someone help me? Thank you in advance!!!
The problem is with b=occ(p+pivot,dim-pivot,X); when pivot is 0. i.e. when dim is 1.
the next function call becomes occ(p,1,X); This again leads to the call occ(p,1,X); in a continuous loop.
It can be fixed by adding a condition to the call, as shown in the code below.
int occ(int *p,int dim,int X){
int pivot,a=0,b=0;
pivot=(dim)/2;
if(dim==0){
return 0;
}
if(*(p+pivot)==X)
return 1;
if (pivot != 0)
{
a=occ(p,pivot,X);
b=occ(p+pivot,dim-pivot,X);
}
if(a+b>=1)
return 1;
else{
return 0;
}
}
The implemetation is causing a stack overflow, as the recursion does not terminate if the input contains only one element. This can be fixed as follows.
int occ(int *p, int dim, int X)
{
int pivot, a, b;
pivot = (dim) / 2;
if (dim == 0)
{
return 0;
}
if (*(p + pivot) == X)
{
return 1;
}
if (dim == 1)
{
if (*(p + pivot) == X)
{
return 1;
}
else
{
return 0;
}
}
a = occ(p, pivot, X);
b = occ(p + pivot, dim - pivot, X);
if (a + b >= 1)
{
return 1;
}
else
{
return 0;
}
}
It's enought to change only this one line in the source code to avoid the endless loop with occ(p,1,X):
//if(dim==0) //end of array
if (pivot == 0)
return 0;

number of zeros runtime error

This is a function i made to count number of zeroes at the end of the factorial of a number b recursively.
However i'm getting runtime error due to the used code.Pardon my naivety but any help in this would be appreciated.
int noz(int b)
{
int c=0;
int e = b;
if(e < 5)
return 0;
while(e > 0)
c = c + (e/5) + noz(e/5);
return c;
}
You are encountering "runtime error" because:
int c;
...
while(e > 0)
c = c + (e/5) + noz(e/5); // <-- HERE
you are using uninitialized local variable c, which produces undefined behavior.
You could zero-initialize this variable to prevent it happen:
int c = 0;
And also note that in case that argument of your function is greater or equal than 5, this function doesn't return anything (thanks to #Paul R for pointing this out) and another problem is that you have loop with the condition e > 0 but the loop doesn't change the value of e making it infinite loop.
Your function could look like this instead (I'm not sure what exactly is the desired logic here):
int noz(int b)
{
int c = 0;
if (b < 5)
return 0;
else
return c + (b/5) + noz(b/5);
}
//count n! tail zero
int noz(int n){
int count;
if(n < 5) return 0;
count = n / 5;
return count + noz(count);
}

UVA's 3n+1 wrong answer although the test cases are correct . . .?

UVA problem 100 - The 3n + 1 problem
I have tried all the test cases and no problems are found.
The test cases I checked:
1 10 20
100 200 125
201 210 89
900 1000 174
1000 900 174
999999 999990 259
But why I get wrong answer all the time?
here is my code:
#include "stdio.h"
unsigned long int cycle = 0, final = 0;
unsigned long int calculate(unsigned long int n)
{
if (n == 1)
{
return cycle + 1;
}
else
{
if (n % 2 == 0)
{
n = n / 2;
cycle = cycle + 1;
calculate(n);
}
else
{
n = 3 * n;
n = n + 1;
cycle = cycle+1;
calculate(n);
}
}
}
int main()
{
unsigned long int i = 0, j = 0, loop = 0;
while(scanf("%ld %ld", &i, &j) != EOF)
{
if (i > j)
{
unsigned long int t = i;
i = j;
j = t;
}
for (loop = i; loop <= j; loop++)
{
cycle = 0;
cycle = calculate(loop);
if(cycle > final)
{
final = cycle;
}
}
printf("%ld %ld %ld\n", i, j, final);
final = 0;
}
return 0;
}
The clue is that you receive i, j but it does not say that i < j for all the cases, check for that condition in your code and remember to always print in order:
<i>[space]<j>[space]<count>
If the input is "out of order" you swap the numbers even in the output, when it is clearly stated you should keep the input order.
Don't see how you're test cases actually ever worked; your recursive cases never return anything.
Here's a one liner just for reference
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
Not quite sure how your code would work as you toast "cycle" right after calculating it because 'calculate' doesn't have explicit return values for many of its cases ( you should of had compiler warnings to that effect). if you didn't do cycle= of the cycle=calculate( then it might work?
and tying it all together :-
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
int max_int(int a, int b) { return (a > b) ? a : b; }
int min_int(int a, int b) { return (a < b) ? a : b; }
int main(int argc, char* argv[])
{
int i,j;
while(scanf("%d %d",&i, &j) == 2)
{
int value, largest_cycle = 0, last = max_int(i,j);
for(value = min_int(i,j); value <= last; value++) largest_cycle = max_int(largest_cycle, three_n_plus_1(value));
printf("%d %d %d\r\n",i, j, largest_cycle);
}
}
Part 1
This is the hailstone sequence, right? You're trying to determine the length of the hailstone sequence starting from a given N. You know, you really should take out that ugly global variable. It's trivial to calculate it recursively:
long int hailstone_sequence_length(long int n)
{
if (n == 1) {
return 1;
} else if (n % 2 == 0) {
return hailstone_sequence_length(n / 2) + 1;
} else {
return hailstone_sequence_length(3*n + 1) + 1;
}
}
Notice how the cycle variable is gone. It is unnecessary, because each call just has to add 1 to the value computed by the recursive call. The recursion bottoms out at 1, and so we count that as 1. All other recursive steps add 1 to that, and so at the end we are left with the sequence length.
Careful: this approach requires a stack depth proportional to the input n.
I dropped the use of unsigned because it's an inappropriate type for doing most math. When you subtract 1 from (unsigned long) 0, you get a large positive number that is one less than a power of two. This is not a sane behavior in most situations (but exactly the right one in a few).
Now let's discuss where you went wrong. Your original code attempts to measure the hailstone sequence length by modifying a global counter called cycle. However, the main function expects calculate to return a value: you have cycle = calculate(...).
The problem is that two of your cases do not return anything! It is undefined behavior to extract a return value from a function that didn't return anything.
The (n == 1) case does return something but it also has a bug: it fails to increment cycle; it just returns cycle + 1, leaving cycle with the original value.
Part 2
Looking at the main. Let's reformat it a little bit.
int main()
{
unsigned long int i=0,j=0,loop=0;
Change these to long. By the way %ld in scanf expects long anyway, not unsigned long.
while (scanf("%ld %ld",&i,&j) != EOF)
Be careful with scanf: it has more return values than just EOF. Scanf will return EOF if it is not able to make a conversion. If it is able to scan one number, but not the second one, it will return 1. Basically a better test here is != 2. If scanf does not return two, something went wrong with the input.
{
if(i > j)
{
unsigned long int t=i;i=j;j=t;
}
for(loop=i;loop<=j;loop++)
{
cycle=0;
cycle=calculate(loop );
if(cycle>final)
{
final=cycle;
}
}
calculate is called hailstone_sequence_length now, and so this block can just have a local variable: { long len = hailstone_sequence_length(loop); if (len > final) final = len; }
Maybe final should be called max_length?
printf("%ld %ld %ld\n",i,j,final);
final=0;
final should be a local variable in this loop since it is separately used for each test case. Then you don't have to remember to set it to 0.
}
return 0;
}

Resources