Rafal Strus
Rafal Strus

Reputation: 60

Sum of big numbers sequence

#include <stdio.h>

int main() {
    unsigned long int sum = 0LL;
    long i;
    for (i = 0LL; i < 100000000; i++) {
        sum = sum + i;
    }
    printf("%i", sum);
}

that's all of my code, and I am curious why it prints 887459712 instead of 4999999950000000, and how to fix this

Upvotes: 1

Views: 53

Answers (1)

abelenky
abelenky

Reputation: 64682

Your sum is declared unsigned long int, which is big enough for your expected result.
The problem is not overflow.

The problem is your printf statement is wrong.

You told it to print a "normal" sized int with %i, which only goes up to about 4.2 billion.

You should tell printf to print an unsigned long int, using %llu
It should be:

printf("%llu", sum);

IDEOne Link

Results

Success #stdin #stdout 0s 5376KB
4999999950000000

Upvotes: 5

Related Questions