Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate powers of 2 using left shift operator for large powers?

Tags:

c#

I want to calculate powers of two without using Math.Pow because i want to avoid using double. So I need a whole integer value. I thought that I could just use the left shift operator but when my power goes past 30, it gives a negative number for power 31, and 1 for powers larger than 31.

My method looks like

    public static long TwoPowX(int power)
    {
        return (1 << power);
    }

Any ideas? Or alternative method?

EDIT: I need to go as high as power 96 maybe more.

2^96 = 79,228,162,514,264,337,593,543,950,336.

like image 257
erotavlas Avatar asked Feb 09 '23 21:02

erotavlas


2 Answers

The literal 1 is an int, so the whole expression (1 << power) will also be evaluated as int and overflow before being converted to long. Use 1L instead.

public static long TwoPowX(int power)
{
    return (1L << power);
}
like image 180
Jakub Lortz Avatar answered Feb 15 '23 11:02

Jakub Lortz


What is the maximum power? Since int consists of 32 bits (31 bits for positive numbers) you get an overflow.

You can use long instead, but then keep in mind the maximum will be a power of 63.

return (long) 1 << power;
like image 28
Abir Avatar answered Feb 15 '23 11:02

Abir