求2^p的方法,p很大

来源:互联网 发布:miloqq群排名优化 编辑:程序博客网 时间:2024/04/19 17:41




int anPow[LEN]; //存放不断增长的2 的次幂
int aResult[LEN]; //存放最终结果的末500 位
scanf("%d", & p);
printf("%d\n", (int)(p*log10(2))+1);
//下面将2 的次幂初始化为2^(2^0)(a^b 表示a 的b 次方),
// 最终结果初始化为1
anPow[0]=2;
aResult[0]=1;
for (i=1;i<LEN;i++) {
anPow[i]=0;
aResult[i]=0;
}



//下面计算2 的p 次方
while (p>0) { // p = 0 则说明p 中的有效位都用过了,不需再算下去
 if ( p & 1 ) //判断此时p 中最低位是否为1
 Multiply(aResult, anPow);
p>>=1;
Multiply(anPow, anPow);//这是两个数相乘的函数
}





源代码如下:

1. #include <stdio.h>
2. #include <memory.h>
3. #define LEN 125 //每数组元素存放十进制的4 位,因此数组最多只要125 个元素即可。
4. #include <math.h>
5. /* Multiply 函数功能是计算高精度乘法 a * b
6. 结果的末 500 位放在a 中
7. */
8. void Multiply(int* a, int* b)
9. {
10. int i, j;
11. int nCarry; //存放进位
12. int nTmp;
13. int c[LEN]; //存放结果的末500 位
14. memset(c, 0, sizeof(int) * LEN);
15. for (i=0;i<LEN;i++) {
16. nCarry=0;
17. for (j=0;j<LEN-i;j++) {
18. nTmp=c[i+j]+a[j]*b[i]+nCarry;
19. c[i+j]=nTmp%10000;
20. nCarry=nTmp/10000;
21. }
22. }
23. memcpy( a, c, LEN*sizeof(int));
24. }
25. int main()
26. {
27. int i;
28. int p;
29. int anPow[LEN]; //存放不断增长的2 的次幂
30. int aResult[LEN]; //存放最终结果的末500 位
31. scanf("%d", & p);
32. printf("%d\n", (int)(p*log10(2))+1);
33. //下面将2 的次幂初始化为2^(2^0)(a^b 表示a 的b 次方),
34. // 最终结果初始化为1
35. anPow[0]=2;
36. aResult[0]=1;
37. for (i=1;i<LEN;i++) {
38. anPow[i]=0;
39. aResult[i]=0;
40. }
42. //下面计算2 的p 次方
43. while (p>0) { // p = 0 则说明p 中的有效位都用过了,不需再算下去
44. if ( p & 1 ) //判断此时p 中最低位是否为1
45. Multiply(aResult, anPow);
46. p>>=1;
47. Multiply(anPow, anPow);
48. }
50. aResult[0]--; //2 的p 次方算出后减1
52. //输出结果
53. for (i=LEN-1;i>=0;i--) {
54. if (i%25==12)
55. printf("%02d\n%02d", aResult[i]/100,
56. aResult[i]%100);
57. else {
58. printf("%04d", aResult[i]);
59. if (i%25==0)
60. printf("\n");
61. }
62. }
63. return 0;
64. }

原创粉丝点击