C版本:
#include<stdio.h>
unsigned int f2(int n);
//判断无符号整数d是不是[2的n次幂]的幂,并指出该数[d]是[2的n次幂]的多少(e)次幂
//原理:2的n次幂的幂的二进制位中有且只有一位是1,且1后面刚好是n个0为一组
int IsPowerof2Power(unsigned int d, int n, int *e)
{
int i = sizeof(d) << 3; //这里i得到d所占的位数(bits),因为要对d的每一位作判断
unsigned int v;
while(i > 0)
{
v = f2(n) & d; //取得d的最后n位
d >>= n;
if(v == 1)
{
if(d == 0)
{
*e = (int)((sizeof(d) << 3) - i) / n;
return 1; //是2^n的幂
}
else
return 0; //不是2^n的幂
}
else if(v == 0)
i -= n;
else
break;
}
return 0;
}
unsigned int f2(int n) //求2^n-1
{
unsigned d = 1;
d <<= n;
d -= 1;
return d;
}
void main()
{
unsigned int i = 2; //1是任何非零数的0次幂
int n, e, n2;
printf("此程序用来判断某个无符号整数是不是2的n次幂的幂,请输入n(大于0): ");
scanf("%d", &n);
while(i < 999999999) //4294967296 = 2^32
{
if((n > 0) && IsPowerof2Power(i, n, &e))
{
n2 = 1 << n;
printf("%d is %d's Power, %d = %d^%d/n", i, n2, i, n2, e);
}
i += 2;
}
}