[Bug c/65855] New: missing optimization: triangular numbers

shawn at churchofgit dot com gcc-bugzilla@gcc.gnu.org
Thu Apr 23 04:52:00 GMT 2015


            Bug ID: 65855
           Summary: missing optimization: triangular numbers
           Product: gcc
           Version: 5.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: shawn at churchofgit dot com

Created attachment 35388
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=35388&action=edit

If a register mode is available to avoid multiplication overflow, a loop that
is calculating triangular numbers could be optimized to a multiplication:

uint64_t triangle(uint32_t n) {
uint64_t t = 0;
for (uint64_t i=1;i<=n;i++) t += i;
return t;


uint64_t triangle_fast(uint32_t _n) {
uint64_t t, n = _n;
t = (n * (n + 1)) / 2;
return t;

More information about the Gcc-bugs mailing list