I am solving a problem to find sum of all prime numbers till 2million, in C. I am continuously getting wrong answer (1179908154) but when i wrote the same code in c++, it gave the correct answer (142913828922). Please tell me why is it so, thank you.
Here is my code
void main()
{
int i,j;
unsigned long long sum;
for(sum=2,i=3;i<=2000000;i+=2)
{
for(j=3;j*j<=i;j++)
if(i%j==0)
break;
if(j*j>i)
sum+=i;
}
printf("%d",sum);
}
I am on windows 7, 32 bit and using GNU GCC v4.7.1
%d
tells printf
to expect an int
argument. sum
is an unsigned long long
. This is undefined behaviour. You probably want printf("%llu\\n", sum);
.
int
isn't a suitable type to be storing values up to 20000000
; The implementation isn't required to be able to represent values beyond -32767
or 32767
using an int
. You probably want i
and j
to be an unsigned long
(suitable to represent positive values up to 0xFFFFFFFFUL
) or an unsigned long long
(suitable to represent positive values up to 0xFFFFFFFFFFFFFFFFULL
). If you're working with values beyond that, you might want to consider using an arbitrary precision arithmetic library such as gmplib .
void main()
isn't a valid entry point in C. You probably want int main()
.
Change type of i
and j
to long
... and use %ld
as format specifier. In c your value is crossing range of integer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.