difference_of_squares.c (617B)

1 #include <stdio.h> 2 3 // The sum of the first N natural numbers can be calculated as 4 // N * (N + 1) / 2. To get the square, we multiply the sum with itself. 5 // This formula saves us from having to loop up to N. 6 int square_of_sum(int n) { 7 return ((n * (n + 1)) / 2) * ((n * (n + 1)) / 2); 8 } 9 10 // The sum of the squares of the first N natural numbers can be 11 // calculated as (n * (n + 1) * ((2 * n) + 1)) / 6. 12 // This formula saves us from having to loop up to N. 13 int sum_of_squares(int n) { 14 return (n * (n + 1) * ((2 * n) + 1)) / 6; 15 } 16 17 int difference_of_squares(int n) { 18 return square_of_sum(n) - sum_of_squares(n); 19 }