C,是一种信仰

如何在 C 中使用 64 位整数?

首先:ANSI C99标准中并没有64位整数类型。其次,许多实际的编译器,都实现了对64位整数类型的支持。
具体的分析,参见:http://blog.csdn.net/lychee007/archive/2010/04/04/5449237.aspx
其中关键是这个表格:

变量定义 输出方式 gcc(mingw32) g++(mingw32) gcc(linux i386) g++(linux i386) MicrosoftVisual C++ 6.0
long long “%lld” 错误 错误 正确 正确 无法编译
long long “%I64d” 正确 正确 错误 错误 无法编译
__int64 “lld” 错误 错误 无法编译 无法编译 错误
__int64 “%I64d” 正确 正确 无法编译 无法编译 正确
long long cout 非C++ 正确 非C++ 正确 无法编译
__int64 cout 非C++ 正确 非C++ 无法编译 无法编译
long long printint64() 正确 正确 正确 正确 无法编译

我们注意到,VC++ 6.0对64位整数的支持是最“那个”的。

重新给出书中的代码:2.4.3 64位整数

题目:输入正整数,统计它的正因子个数。n<=(10的12次方)

标准C语言的解法:
编译器:TCC(基本上就是C99的国际标准,可厉害了!)

0001 /*

0002     2.4.3,64位整数
0003     例子
0004     输入正整数n,统计它的正因子个数
0005     n<=(10的12次方)

0006     
0007     解题思路:
0008         穷举法,从1开始,穷举每个可能的因子x;对于满足条件(n%x==0)的,将计数器count增量1
0009         穷举的技巧:

0010             只需要穷举[1..sqrt(n)]的范围即可;
0011             如果x是n的因子,那么(n/x)也是n的因子。
0012 
0013      

0014 */
0015 # include "stdio.h"
0016 # include "math.h"
0017 void main() {

0018     long long n,
0019         x,  /*假设的因子*/
0020         count=0; /*计数器*/

0021 
0022     scanf("%I64d",&n);
0023     for (x=1; x<=(long long)sqrt(n); x=x+1) {        

0024         if (n%x==0) {
0025             count=count+2; /*之所以+2,是因为x和(n/x)都是n的因子*/

0026             /* printf("%I64d\n",x); */
0027             if (n/x==x) count=count-1;
0028         }

0029     }
0030     printf("因子个数:%I64d",count);
0031 
0032     return;

0033 }

上述代码写得本身没有什么问题,但是在VC++ 6.0中编译时,会被告知:

……test.c(4) : error C2632: 'long' followed by 'long' is illegal

这就是VC++ 6.0不能识别 long long 的明证!
那么,VC++ 6.0要如何完成上述代码中所需的64位整数呢?
请看下面的代码:(唯一的秘诀就是把 long long 改成 __int64;注意:int64 的左边有两个下划线哦!

0001 # include "stdio.h"

0002 # include "math.h"
0003 void main() {
0004     __int64 n,
0005         x,  /*假设的因子*/

0006         count=0; /*计数器*/
0007 
0008     scanf("%I64d",&n);

0009     printf("%I64d",n);
0010     for (x=1; x<=(__int64)sqrt(n); x=x+1) {        

0011         if (n%x==0) {
0012             count=count+2; /*之所以+2,是因为x和(n/x)都是n的因子*/

0013             /* printf("%I64d\n",x); */
0014             if (n/x==x) count=count-1;
0015         }

0016     }
0017     printf("因子个数:%I64d",count);
0018     return;
0019 }

请注意,上述代码,均可以正确处理10的12次方以内的超大整数的数据输入。
不信?你试试看!

posted @ 2011-01-21 21:00  胖乎乎的王老师  Views(2257)  Comments(1Edit  收藏  举报
Email 联系我:fzd19zx@qq.com