Home > Software design >  Sum of big numbers sequence
Sum of big numbers sequence

Time:04-22

#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

CodePudding user response:

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
  •  Tags:  
  • c
  • Related