Home > OS >  Why the output of this function is 0 when n=100?
Why the output of this function is 0 when n=100?

Time:07-31

int f(int n)
{
    static int r=0;
    if(n<=0)
    {
        return 1;
    }
    if(n>3)
    {
        r=n;
        return f(n-2)*2;
    }
    return f(n-1) r;
}

When n=10 or n=50 I am getting a positive integer as output but when n is in the range 70 to 100 I am getting 0 as output. According to my knowledge if out of range of int occurs then it will follow a circular order and start again from 0 but in this case, it is always getting 0 as an output. Can you please explain the reason?

CodePudding user response:

Let's look at this line.

f(n-2)*2;

Note that ints are stored in binary. This is equivalent to getting the value of f(n-2), and shifting all of its bits one space to the left. (If f(n-2) were to be unsigned, the expression would be equivalent to f(n-2)<<1).

For sufficiently large values of n, if you keep on shifting bits to the left, you'll end up with 0 when the int eventually overflows.

It seems, in your case, that value of n is 59, although due to your program logic, n = 60, 62, 64 all give non-zero results.

CodePudding user response:

Yes, Your problem is because of being Out Of Rane. It shows always zero because the LSB part of that is zero. As I calculated the return value, that is 9*2^49, which is 5,066,549,580,791,808 decimal and if you convert it to hexadecimal form, It would be 0x12000000000000. This is totally out of range of an int variable. So It is better to use int64_t from stdint.h to use that.
Note that for printf you have to split it to two 32bit number.
The code below may be help you.

#include <stdio.h>
#include <stdint.h>

int64_t f(int64_t n)
{
    static int64_t r=0;
    if(n<=0)
    {
        return 1;
    }
    if(n>3)
    {
        r=n;
        return f(n-2)*2;
    }
    return f(n-1) r;
}

int main()
{
    int64_t retf = f(100);
    printf("MSB ret: 0x%x\n", (int)(retf >> 32));
    printf("LSB ret: 0x%x\n", (int)retf);
    return 0;
}
  • Related