- 论坛徽章:
- 14
|
随手写个快速幂算法- #include <stdio.h>
- unsigned long long pown( unsigned a, unsigned b )
- {
- unsigned long long ret = 1;
- for( unsigned long long tmp=a; b; b>>=1, tmp*=tmp )
- {
- if( b&1 )
- ret *= tmp;
- }
- return ret;
- }
- int main()
- {
- printf( "3^35 = %llu\n", pown(3,35) ); // 50031545098999707
- printf( "3^36 = %llu\n", pown(3,36) ); // 150094635296999121
- return 0;
- }
复制代码 在VC++9.0上用C++方式编译,运行结果正确。
但在MinGW4.8.1上用C99方式编译,运行结果却不正确,因为MinGW不认识%llu,这简直是太扯淡了。
不得已,再改一下代码- #include <stdio.h>
- #include <inttypes.h>
- uint64_t pown( unsigned a, unsigned b )
- {
- uint64_t ret = 1;
- for( uint64_t tmp=a; b; b>>=1, tmp*=tmp )
- {
- if( b&1 )
- ret *= tmp;
- }
- return ret;
- }
- int main()
- {
- printf( "3^35 = %"PRIu64"\n", pown(3,35) ); // 50031545098999707
- printf( "3^36 = %"PRIu64"\n", pown(3,36) ); // 150094635296999121
- return 0;
- }
复制代码 |
|