I wrote some program in C language. I have to calculate sum of squares. My book suggested me to use loops but I chose more efficient way by using formula:
$$1^2+2^2+\cdots+n^2=\frac{n\left(n+1\right)\left(2n+1\right)}{6}$$
Original code from listing 5.13:
#include <stdio.h> int main(void) { int ilicznik, sum;suma; ilicznik = 0; sumsuma = 0; while (i++licznik++ < 20) sumsuma = sumsuma + i;licznik; printf("Sum"suma = %d\n", sumsuma); return 0; }
Finally, this is my code:
#include <stdio.h>
int main(void) {
int range;zakres;
printf("Enter the range"Podaj ofzakres theprzeprowadzanych calculationobliczen:\n");
scanf("%i", &range&zakres);
printf("Sum of"suma squareskwadratow = %d\n", (((rangezakres * (rangezakres + 1)) * (2 * rangezakres + 1)) / 6));
return 0;
}
What do you think about this solution? Is it more efficient than loops?