- 论坛徽章:
- 1
|
修改了一下代码
1. 在改成了windows下vc 2005可以编译运行的
2. 参照zliming, 位图使用int*代替char*
说明一下, 位图的存取必须用宏或者inline(编译器优化成inline的也可以), 否则函数调用的开销非常大。
运行结果:
Total: 455052511, Time: 904
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <string.h>
- #define CLEAR(map, bit) (map)[(bit) / 32] &= ~(1 << (bit % 32))
- #define GET(map, bit) ((map)[(bit) / 32] & (1 << (bit % 32)))
- const static long long SQUARE_ROOT = 100000;
- const static long long BOUND = SQUARE_ROOT * SQUARE_ROOT;
- int main() {
- unsigned long long i = 0;
- int start = time(NULL);
- int* map = (int*)malloc(BOUND / 8 + 1);
- if (map == 0) {
- printf("Oh no\n");
- exit(1);
- }
- memset(map, 0xff, BOUND / 8 + 1);
- CLEAR(map, 1);
- for (i = 1; i < SQUARE_ROOT; i++) {
- if (!GET(map, i)) continue;
- printf("%lld\n", i);
- long long j = i * 2;
- for (; j < BOUND; j += i) {
- CLEAR(map, j);
- }
- }
- long long total = 0;
- for (i = 1; i < BOUND; i++) {
- if (GET(map, i)) {
- total++;
- }
- }
- printf("Total: %lld, Time: %d\n", total, time(NULL) - start);
- system("pause");
- }
复制代码
[ 本帖最后由 koolcoy 于 2009-4-22 10:51 编辑 ] |
|