Calculating sum of squares in C 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 &lt;stdio.h&gt;

int main(void) {
    int licznik, suma;

    licznik = 0;
    suma = 0;
    while (licznik++ &lt; 20)
        suma = suma + licznik;
    printf("suma = %d\n", suma);
    return 0;
}



Finally, this is my code:

#include &lt;stdio.h&gt;

int main(void) {
    int zakres;
    printf("Podaj zakres przeprowadzanych obliczen:\n");
    scanf("%i", &amp;zakres);
    printf("suma kwadratow = %d\n", (((zakres * (zakres + 1)) * (2 * zakres + 1)) / 6));
    return 0;
}


What do you think about this solution? Is it more efficient than loops?
Well, I can't say much about your naming, as I cannot read it. For a wider audience than a purely local team - and probably even then - consider switching to english.

What I can tell is that you are very generous with parentheses. Using them everywhere actually reduces readability, you know?

Next, congratulations for working smarter instead of harder, it really pays in speed.
Though there is a down-side to your implementation of the modified algorithm: It encounters Undefined Behavior due to integer-overflow slightly before the brute-force-one does (by about five to six numbers). Why are you using signed arithmetic anyway?

And then you assume the programs input is always well-formed. You know scanf() can fail? So, test the return-value.