From 61d8d8a336ca9a74eaf0e77e6ec9ab59f8bccddb Mon Sep 17 00:00:00 2001 From: Andinus Date: Wed, 25 Aug 2021 20:07:15 +0530 Subject: C: Improve difference-of-squares Use sum of series instead of calculating it. --- .../src/difference_of_squares.c | 32 +++------------------- 1 file changed, 4 insertions(+), 28 deletions(-) (limited to 'c/difference-of-squares') diff --git a/c/difference-of-squares/src/difference_of_squares.c b/c/difference-of-squares/src/difference_of_squares.c index 8a422eb..27311ec 100644 --- a/c/difference-of-squares/src/difference_of_squares.c +++ b/c/difference-of-squares/src/difference_of_squares.c @@ -1,38 +1,14 @@ #include "difference_of_squares.h" #include -/* - Returns the sum of squares upto nth Natural number. - - The difference in squares increases by a incrementing (by 2) step. - - Sequence: - 1 4 9 16 25 36 49 64 81 100 - - 4 - 1 = 3 - 9 - 4 = 5 (3 + 2 = 5) - 16 - 9 = 7 (5 + 2 = 7) - - step is our incrementing step, we increment it by 2 in every - iteration and add it to previous square to get the current term. -*/ +// Returns the sum of squares upto nth Natural number. unsigned int sum_of_squares(unsigned int number) { - unsigned int sum = 1; - unsigned int step = 1; - unsigned int prev_sq = 1; - for (; number > 1; number--) { - step += 2; - prev_sq += step; - sum += prev_sq; - } - return sum; + return (number * (number + 1) * (2 * number + 1)) / 6; } +// Returns the square of sum upto nth Natural number. unsigned int square_of_sum(unsigned int number) { - unsigned int sum = 0; - for (; number > 0; number--) - sum += number; - return pow(sum, 2); + return pow((number * (1 + number)) / 2, 2); } unsigned int difference_of_squares(unsigned int number) { -- cgit 1.4.1-2-gfad0