Skip to content
Assembly

Loop Summation (1..N)

Sum integers 1..N with a counted loop using dec/jnz.

By EZ4Code Team
loopsarithmeticcontrol-flow

Code

; sum_to(N) -> 1+2+...+N    rdi=N, result in rax
section .text
global sum_to

sum_to:
    xor     eax, eax        ; accumulator = 0
    test    edi, edi
    jle     .done           ; if N <= 0, return 0

.loop:
    add     eax, edi        ; accumulate N, N-1, ...
    dec     edi
    jnz     .loop           ; repeat until edi == 0

.done:
    ret

; Faster closed form:  sum(N) = N*(N+1)/2
global sum_to_fast
sum_to_fast:
    mov     eax, edi
    add     eax, 1          ; N+1
    imul    eax, edi        ; N*(N+1)
    shr     eax, 1          ; /2
    ret

Explanation

The loop uses dec/jnz instead of the slower 'loop' instruction. Working in 32-bit (eax/edi) keeps the encoding small and is enough for moderate N. The second version uses the closed-form N*(N+1)/2 — compilers often do this transformation (loop strength reduction) and it's O(1) instead of O(N). shr by 1 is the same as unsigned /2.

More Assembly Snippets