优质解答
给你提供三种方法,你自己根据其优劣进行选择.
#include
#define N 64
/*方法一*/
unsigned _int64 fun_1( )
{
unsigned _int64 sum = 0,item = 1;
int i;
for(i = 0; i < N; i++)
{
sum += item;
item *= 2;
}
return sum;
}
/*方法二*/
unsigned _int64 fun_2( )
{
unsigned _int64 sum = 0;
int i;
for(i = 0; i < N; i++)
sum = sum * 2 + 1;
return sum;
}
/*方法三 2^0+2^1+2^2+.+2^(n-1) = 2^n - 1,因此直接求2^64-1即可,计算结果的二进制即为64个连续的1,即printf("%I64u\n",0xffffffffffffffff); 如果要用算法去计算的话,则先求s=pow(2,64),然后再求s - 1,但2^64对于64位整型变量都会溢出哦,不考虑溢出的话,可如下*/
unsigned _int64 pow(int x,int y) /*求x^y*/
{
unsigned _int64 tmp;
if(y == 0) return 1;
tmp = pow(x,y / 2);
if(y % 2 == 0) return tmp * tmp;
else return tmp * tmp * x;
}
unsigned _int64 fun_3( )
{
return pow(2,N) - 1;
}
void main()
{
printf("%I64u\n",fun_1()); /*方法一*/
printf("%I64u\n",fun_2()); /*方法二*/
printf("%I64u\n",0xffffffffffffffff); /*方法三*/
}