Your code does get the correct answer.
There's no reason to worry about overflow with limit set to 100, alghouth if it was necessary you can calculate it using the forumula for the sum of numbers from 1 to Limit and the quadratic formula.
But you shouldn't declare all your variables at the top of a function.
I might write it more like this:
Code:
#include <stdio.h>
typedef unsigned long long ull;
int main()
{
const ull Limit = 100;
ull squares_sum = 0;
// 1**2 + 2**2 + 3**2 + ... + Limit**2
for (ull i = 1; i <= Limit; ++i)
squares_sum += i * i;
//printf("%llu\n", squares_sum);
ull sum_square = 0;
// 1 + 2 + 3 + ... + Limit
for (ull i = 1; i <= Limit; i++)
sum_square += i;
sum_square *= sum_square;
//printf("%llu\n", sum_square);
printf("%llu\n", sum_square - squares_sum);
return 0;
}
And here's the way to do it using formulas instead of loops.
I calculated the highest Limit that won't overflow an unsigned 64-bit value.
Code:
#include <stdio.h>
#define FORMAT "%20llu"
typedef unsigned long long ull;
int main()
{
const ull Limit = 92681; // as high as we can go using 64-bit unsigned
ull sum = Limit * (Limit + 1) / 2;
ull sum_of_squares = sum * (2 * Limit + 1) / 3;
ull square_of_sum = sum * sum;
printf("sum_of_squares: "FORMAT"\n", sum_of_squares);
printf("sum : "FORMAT"\n", sum);
printf("square_of_sum : "FORMAT"\n", square_of_sum);
printf("difference : "FORMAT"\n", square_of_sum - sum_of_squares);
return 0;
}