NOrder
NOrder

Reputation: 2493

how to calculate 2^32 without multiplying numbers directly?

the simplest way to calculate 2^32 is 2*2*2*2*2......= 4294967296 , I want to know that is there any other way to get 4294967296? (2^16 * 2^16 is treated as the same method as 2*2*2.... )

and How many ways to calculate it?
Is there any function to calculate it?

I can't come up with any methods to calculate it without 2*2*2...

Upvotes: 1

Views: 4670

Answers (6)

William Breathitt Gray
William Breathitt Gray

Reputation: 11986

If you are on a common computer you can left bitshift 2 by 31 (i.e. 2<<31) to obtain 2^32.

In standard C:

unsigned long long x = 2ULL << 31;

unsigned long long is needed since a simple unsigned long is not guaranteed to be large enough to store the value of 2<<31.

In section 5.2.4.2.1 paragraph 1 of the C99 standard:

... the following shall be replaced by expressions that have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign.

— maximum value for an object of type unsigned long int

ULONG_MAX 4294967295 // 2^32 - 1

— maximum value for an object of type unsigned long long int

ULLONG_MAX 18446744073709551615 // 2^64 - 1

Upvotes: 1

Hemant
Hemant

Reputation: 4616

In Groovy/Java you can do something like following with long number (signed integer can be max 2^31 in Java)

long twoPOW32 = 1L << 32;

Upvotes: 0

King King
King King

Reputation: 63347

Why not using Math.Pow() (in .NET). I think most language (or environment) would support the similar function for you:

Math.Pow(2,32);

Upvotes: 0

Aravind
Aravind

Reputation: 3199

If you are not much of a fan of binary magic, then I would suggest quickpower.This function computes xn in O(logn) time.

 int qpower(int x,int n)
 {
   if(n==0)return 1;
   if(n==1)return x;
   int mid=qpower(x,n/2);
   if(n%2==0)return mid*mid;
   return x*mid*mid;
 }

Upvotes: 1

Timothy Shields
Timothy Shields

Reputation: 79531

Options:

  1. 1 << 32
  2. 2^32 = (2^32 - 1) + 1 = (((2^32 - 1) + 1) - 1) + 1 = ...
  3. Arrange 32 items on a table. Count the ways you can choose subsets of them.

Upvotes: 1

Robert Harvey
Robert Harvey

Reputation: 180858

2 << 31

is a bit shift. It effectively raises 2 to the 32nd power.

Upvotes: 9

Related Questions