From 61cea0dd0cadb68a5a9cacd8a2e029cc5848e87b Mon Sep 17 00:00:00 2001 From: dwrz Date: Fri, 7 Jun 2019 02:37:02 +0000 Subject: [PATCH] Refactor c/difference-of-squares Curious to benchmark the different approaches. --- .../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 index 83c1c06..9f9ac03 100644 --- 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 +// 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) {