Find the sum of all the primes below two million. Project euler, C -


so, seems working nicely, program doesn't give me correct answer. mine 142,915,960,832, whereas should 142,913,828,922. differece 2,131,910 (if still can subtract numbers on paper haha) , have no idea did 2 millions. me?

#include <stdio.h> #include <math.h>  #define below 2000000  int isaprime (int num);  int main (void) {      int i;     float sum = 0;      (i = 2; < below; i++) {              if (isaprime(i) == 1) {                     sum = sum + i;                     printf ("\n%d\t%.1f", i, sum);             }     }      getch();     return 0; }  int isaprime (int num) {      int i;      (i = 2; <= sqrt(num); i++) {             if (num % == 0) {                     return 0;             }             else {                     ;             }     }      return 1; } 

using float sum problem. largest integer k such integers [-k, k] exactly representable in 32-bit float 2^241; after start losing precision in integers. since sum outside range that, absurd margin, lose precision , bets off.

you need change larger type long (assuming it's 64-bits on machine). make change, , you'll right answer (as did code):

[ec2-user@ip-10-196-190-10 ~]$ cat -n euler.c      1  #include <stdio.h>      2  #include <math.h>      3        4  #define below 2000000      5        6  int isaprime (int num);      7        8  int main (void) {      9       10      int i;     11      long sum = 0;     12       13      (i = 2; < below; i++) {     14       15              if (isaprime(i) == 1) {     16                      sum = sum + i;     17              }     18      }     19      printf("sum: %ld\n", sum);     20       21      return 0;     22  }     23       24  int isaprime (int num) {     25       26      int i;     27       28      (i = 2; <= sqrt(num); i++) {     29              if (num % == 0) {     30                      return 0;     31              }     32              else {     33                      ;     34              }     35      }     36       37      return 1;     38  } [ec2-user@ip-10-196-190-10 ~]$ gcc euler.c -lm [ec2-user@ip-10-196-190-10 ~]$ ./a.out sum: 142913828922 

1: 23 explicit bits in mantissa plus 1 hidden bit.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -