Refactor c/difference-of-squares

Curious to benchmark the different approaches.
This commit is contained in:
dwrz
2019-06-07 02:37:02 +00:00
parent f8127fdf4a
commit 61cea0dd0c
@@ -1,16 +1,17 @@
#include <stdio.h>
// The sum of the first N natural numbers can be calculated as
// N * (N + 1) / 2. To get the square, we multiply the sum with itself.
// This formula saves us from having to loop up to N.
int square_of_sum(int n) {
int sum = (n * (n + 1)) / 2;
return sum * sum;
return ((n * (n + 1)) / 2) * ((n * (n + 1)) / 2);
}
// The sum of the squares of the first N natural numbers can be
// calculated as (n * (n + 1) * ((2 * n) + 1)) / 6.
// This formula saves us from having to loop up to N.
int sum_of_squares(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) sum += i * i;
return sum;
return (n * (n + 1) * ((2 * n) + 1)) / 6;
}
int difference_of_squares(int n) {