commit 61cea0dd0cadb68a5a9cacd8a2e029cc5848e87b parent f8127fdf4a562bc6f10f050d04db741120562512 Author: dwrz <dwrz@dwrz.net> Date: Fri, 7 Jun 2019 02:37:02 +0000 Refactor c/difference-of-squares Curious to benchmark the different approaches. Diffstat:
M | c/difference-of-squares/src/difference_of_squares.c | | | 15 | ++++++++------- |
1 file changed, 8 insertions(+), 7 deletions(-)
diff --git a/c/difference-of-squares/src/difference_of_squares.c b/c/difference-of-squares/src/difference_of_squares.c @@ -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) {