https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112663

            Bug ID: 112663
           Summary: missed-optimization: sum of 1 to n
           Product: gcc
           Version: 13.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: goon.pri.low at gmail dot com
  Target Milestone: ---

This code which calculates the sum of 1 + 2 + .. n

unsigned unopt(unsigned n) {
    unsigned k = 0;

    for (unsigned i = 1; i <= n; i++)
        k += i;

    return k;
}

Could be optimized to this mathematical formula:

unsigned opt(unsigned n) {
    return n * (n + 1) / 2;
}
  • [Bug middle-end/112663] New: mi... goon.pri.low at gmail dot com via Gcc-bugs

Reply via email to