Reputation: 2328
I was writing a small program to compare speed between CPP and Matlab, and I noticed I was getting the wrong answer when working with large numbers.
Here's the code:
#include "stdafx.h"
#include <iostream>
#include "time.h"
int main()
{
clock_t t = clock();
long x = 1000000;
long sum = 0;
for (long i = 1;i <= x;i++) {
sum = sum + i;
}
t = clock() - t;
printf("It took %d ms, sum equals=",t);
std::cout << sum << std::endl;
return 0;
}
100 000 returns the right answer, but above 1000 0000 does not. Anyone have an idea what's going on? I can't imagine the problem being overflow because the numbers involved are simply not that big (correct answer is 5e9).
Upvotes: 0
Views: 1261
Reputation: 99
I gave your Programm a test run and it returned the right answer (compared with wolfram alpha). So there isn't an error in the code I would say.
EDIT: run on a 64bit machine, so you may use a 32bit and got the overflow like told in the answer above.
Upvotes: 0
Reputation: 71909
The problem is overflow. 5e9 is 5'000'000'000, but the largest number a 32-bit signed integer (long on 32-bit platforms, and on 64-bit Windows; it's 64-bit on 64-bit Linux) can hold is 2'147'483'648.
Upvotes: 3