Last active
August 29, 2015 14:11
-
-
Save LYP951018/65b6009f3c48425ff263 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //#pragma warning (disable:4996) | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <stdbool.h> | |
| #include <stdint.h> | |
| size_t Capacity = 10u; | |
| void PrintError(void) | |
| { | |
| printf("内存不足,无法进行之后的操作。\n"); | |
| } | |
| uint64_t* ReallocSpace(uint64_t* pPrev) | |
| { | |
| Capacity += (Capacity >> 1); | |
| uint64_t* pRes = (uint64_t*)realloc(pPrev, sizeof(uint64_t)*Capacity); | |
| free(pPrev); | |
| return pRes; | |
| } | |
| int main(void) | |
| { | |
| uint64_t limit = UINT64_C(0); | |
| printf("请输入质数上限值:\n"); | |
| scanf("%llu", &limit); | |
| uint64_t* pPrimes = | |
| (uint64_t*)calloc(Capacity, sizeof(uint64_t)); | |
| if (!pPrimes) | |
| { | |
| PrintError(); | |
| return EXIT_FAILURE; | |
| } | |
| uint64_t Count = UINT64_C(0); | |
| bool IfBreak = false; | |
| if (limit > UINT64_C(1)) | |
| { | |
| pPrimes[Count++] = UINT64_C(2);//start point | |
| for (uint64_t trial = UINT64_C(3); trial < limit; trial+=2) | |
| { | |
| for (uint64_t i = UINT64_C(1); i < Count; ++i) | |
| { | |
| IfBreak = !(trial % pPrimes[i]); | |
| if (IfBreak) break; | |
| } | |
| if (!IfBreak) | |
| { | |
| if (Count == Capacity) | |
| { | |
| pPrimes = ReallocSpace(pPrimes); | |
| if (pPrimes == NULL) | |
| { | |
| PrintError(); | |
| return EXIT_FAILURE; | |
| } | |
| } | |
| pPrimes[Count++] = trial; | |
| } | |
| } | |
| } | |
| printf("%llu primes found up to %llu:\n", Count, limit); | |
| for (uint64_t i = UINT64_C(0) ; i < Count ; ++i) | |
| { | |
| printf("%12llu", *(pPrimes + i)); | |
| if (!((i + 1) % 5)) | |
| printf("\n"); | |
| } | |
| free(pPrimes); | |
| system("pause"); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment