Difference of Squares
Difference of Squares in C



unsigned int sum_of_squares(unsigned int number);
unsigned int square_of_sum(unsigned int number);
unsigned int difference_of_squares(unsigned int number);



#include "difference_of_squares.h"

unsigned int square_of_sum(unsigned int number)
   unsigned int sum = (number * (number + 1)) / 2;
   return sum * sum;

unsigned int sum_of_squares(unsigned int number)
   return (number * (number + 1) * ((number * 2) + 1)) / 6;

unsigned int difference_of_squares(unsigned int number)
   return square_of_sum(number) - sum_of_squares(number);

In this solution a formula is used to solve the square_of_sum and sum_of_squares functions.

At the time of this writing the instructions state:

You are not expected to discover an efficient solution to this yourself from first principles; research is allowed, indeed, encouraged. Finding the best algorithm for the problem is a key skill in software engineering.

It is fine to search for an algorithm on the internet. This is also sometimes referred to as "Google is your friend", although you don't have to search with Google.

It is okay if you don't understand how the algorithm works. What is important is that it obviously is not introducing malware and that it passes the tests.

Note that this avoids using pow in square_of_sum, since multiplying a value by itself is usually more efficient than type-casting from int to double back to int.

29th May 2024 · Found it useful?