修改了 字节数问题方面的一个Bug
程序代码:
#include <stdio.h> #include <malloc.h> #include <string.h> typedef unsigned long LCNT; typedef unsigned long CELL; #define DAT_SIZE 2000000000 #define CELL_SIZE (sizeof(CELL)*8) #define MEM_SIZE (DAT_SIZE/CELL_SIZE + 1) //Fix: MEM_SIZE 表示需要开辟的CELL数组大小 LCNT BitSearch(CELL bitSet[], LCNT startPos); void BitClear(CELL bitSet[], LCNT bitPos); int main() { LCNT i, primSum = 0, primCnt = 2; CELL *primSet = (CELL*)malloc(MEM_SIZE*sizeof(CELL)); //Fix: 开辟MEM_SIZE需要的字节数 if(primSet == NULL){ printf("内存不足\n"); return 1; } else{ memset(primSet, 0xFF, MEM_SIZE*sizeof(CELL)); //Fix: 清空MEM_SIZE需要的字节数 primSet[0] ^= 3; //质数从2开始,自然数[0,1]所在位清零 } while(primCnt < DAT_SIZE){ for(i=2; primCnt*i < DAT_SIZE; i++) BitClear(primSet, primCnt*i); primSum += primCnt; primCnt = BitSearch(primSet, primCnt+1); } printf("The Sum is %ld\n", primSum); return 0; } LCNT BitSearch(CELL bitSet[], LCNT startPos) { LCNT arrPos = startPos/CELL_SIZE, bitPos = startPos%CELL_SIZE; while(arrPos < MEM_SIZE){ if(bitSet[arrPos] != 0){ for(bitPos; bitPos < CELL_SIZE; bitPos++) if((bitSet[arrPos] >> bitPos)%2 == 1) goto OUT; bitPos = 0; } arrPos++; } OUT: return arrPos*CELL_SIZE + bitPos; } void BitClear(CELL bitSet[], LCNT bitPos) { bitSet[bitPos/CELL_SIZE] &= ~((LCNT)1 << bitPos%CELL_SIZE); }
人生是一场错过 愿你别蹉跎