Be careful if you use that code on a 32-bit system. That
multiply would overflow because 1e7 (10,000,000) * 1e7 is 1e14, well over the 2.1e9 signed int32_t limit.
Code:
i * i
$ time ./prime_gcc 664580 real 0m8.030s user 0m8.030s sys 0m0.000s
#include <stdbool.h> #include <stdint.h> #include <stdio.h> // // https://stackoverflow.com/questions/37513311/prime-number-generator-in-c // bool IsPrime(int test) { // i <= sqrt(test) // but to avoid sqrt you can do i * i <= test for(int i= 2; i * i <= test; i++){ if(test%i==0){ return false; } } return true; } int main() { int count=0; for (int i=1;i<1000*1000*10;++i) { if (IsPrime(i)) { count++; } } printf("%d\n",count); }
i * i
Comment