summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndinus <andinus@nand.sh>2021-08-11 19:50:45 +0530
committerAndinus <andinus@nand.sh>2021-08-11 19:50:45 +0530
commitc6d284ed8dcf0c5ef91036669eb20ad8e786a10a (patch)
treed05f880a58be31446e90d2ffc054d5b08d18f34d
parent2f3aeed02b0dda08397bcd421c66f4ac058f38f3 (diff)
downloadexercism-c6d284ed8dcf0c5ef91036669eb20ad8e786a10a.tar.gz
C: Difference of Squares: Finding sum of squares without pow function
-rw-r--r--c/difference-of-squares/src/difference_of_squares.c26
1 files changed, 23 insertions, 3 deletions
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 <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.
+*/
 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;
 }