user3210656
user3210656

Reputation: 21

Find the sum of all the primes below two million. why doesn't my code work?

It should print 142,913,828,922, (and not 1179908154 how it does...) what's wrong?

http://pastebin.com/gJL4cMxm#

#include <stdio.h>
#include <conio.h>
#include <math.h>

int main()
{
    int n=2000000;
    long long sum=0;
    int m;
    int i;
    for(i=2;i<n;i++)
    {
        for(m=2;m<=sqrt(i);m++)
        {
            if(i%m==0)
            {      
                break;
            }
        }
        if(m>sqrt(i))
            sum+=i;
    }
    printf("%d",sum);  
    getch();
}

Upvotes: 0

Views: 102

Answers (2)

barak manos
barak manos

Reputation: 30136

Change:

printf("%d",sum);

To:

printf("%lld",sum);

Explanation:

If the size of variable sum is 4 bytes or less, 4 bytes of data are pushed into the stack before printf is called.

If the size of variable sum is 8 bytes, 8 bytes of data are pushed into the stack before printf is called.

After that, printf("%d"...) will attempt to read 4 bytes of data from the stack.

The size of type long long is 8 bytes on some compilers (including yours probably), hence print("%d",sum) prints only "the lower half" of sum, which is obviously the wrong value in your perspective (unless sum < 2^32).

Upvotes: 5

shivshnkr
shivshnkr

Reputation: 1465

The error lies in the line:

printf ("%d\n", sum);

It should be like :

printf ("%lld\n", sum);

Upvotes: 3

Related Questions