From c6d284ed8dcf0c5ef91036669eb20ad8e786a10a Mon Sep 17 00:00:00 2001 From: Andinus Date: Wed, 11 Aug 2021 19:50:45 +0530 Subject: C: Difference of Squares: Finding sum of squares without pow function --- .../src/difference_of_squares.c | 26 +++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) (limited to 'c') diff --git a/c/difference-of-squares/src/difference_of_squares.c b/c/difference-of-squares/src/difference_of_squares.c index f59e92c..8a422eb 100644 --- a/c/difference-of-squares/src/difference_of_squares.c +++ b/c/difference-of-squares/src/difference_of_squares.c @@ -1,10 +1,30 @@ #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. +*/ unsigned int sum_of_squares(unsigned int number) { - unsigned int sum = 0; - for (; number > 0; number--) - sum += pow(number, 2); + 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; } -- cgit 1.4.1-2-gfad0