Home > other >  How do I do pow without the math.h library?
How do I do pow without the math.h library?

Time:11-02

i have this code:

if (is_prime == 1) {
    for (marsennloop = 1, marsenn = 0; marsennloop <= calc; marsennloop  ) {
        marsennloop = marsennloop * 2;
        marsenncalc2 = marsennloop - 1;
        if (marsenncalc2 == calc && calc != 1) {
            marsenn = 1;
        }
    }
}

on the line "marsennloop = marsennloop * 2;" i am trying to do a pow function without using pow but this give me an incorrect output when i change this line to pow and use the same variables i get the correct output which leads me to believe the problem lies within that line of code.

CodePudding user response:

power of two (2^n) is simply shift 1 << n

So naive function checking if the number is mersenne prime:

int ism(unsigned val)
{
    int result = 0;
    for(unsigned long long i = 2; i <= 1ULL << (CHAR_BIT * sizeof(val)); i <<= 1)
    {
        if(i - 1 == val) 
        {
            result = 1;
            break;
        }
    }
    return result;
}

int main(void)
{
    unsigned count = 0;
    for(unsigned i = 1; i <= (1U << 20); i  )
    {
        if(ism(i)) 
        {
            printf("%u ", i);
            if(!(  count % 16)) printf("\n");
        }
    }
}

CodePudding user response:

If you want to test if the number is 2^n - 1, please try the following function:

int is_m(unsigned int x)
{
    return (x & (x   1)) == 0;
}

It returns 1 if x is 2^n - 1, else returns 0.

  •  Tags:  
  • c
  • Related