diff options
author | Andinus <andinus@nand.sh> | 2021-08-25 20:07:15 +0530 |
---|---|---|
committer | Andinus <andinus@nand.sh> | 2021-08-25 20:07:15 +0530 |
commit | 61d8d8a336ca9a74eaf0e77e6ec9ab59f8bccddb (patch) | |
tree | a5dcf5018a746781be7bb9f13bc998a02feaa0a5 /c/difference-of-squares | |
parent | b5c455ddef1b9f3c112be5db50c0a63d588a67cf (diff) | |
download | exercism-61d8d8a336ca9a74eaf0e77e6ec9ab59f8bccddb.tar.gz |
C: Improve difference-of-squares
Use sum of series instead of calculating it.
Diffstat (limited to 'c/difference-of-squares')
-rw-r--r-- | c/difference-of-squares/src/difference_of_squares.c | 32 |
1 files changed, 4 insertions, 28 deletions
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 <math.h> -/* - 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) { |