帮助改进简单的装配功能

MPe*_*ier 5 x86 assembly

我只是在一项任务中交出了这个功能.它完成了(因此没有家庭作业标签).但我想看看如何改进.

本质上,函数使用以下公式对1和给定数字之间的所有整数的平方求和:

n(n+1)(2n+1)/6
Run Code Online (Sandbox Code Playgroud)

n最大数量在哪里.

下面的函数用于捕获任何溢出,如果发生任何溢出则返回0.

UInt32 sumSquares(const UInt32 number)
{
    int result = 0;
    __asm
    {
        mov eax, number  //move number in eax
        mov edx, 2       //move 2 in edx
        mul edx          //multiply (2n)
        jo end           //jump to end if overflow
        add eax, 1       //addition (2n+1)
        jo end           //jump to end if overflow
        mov ecx, eax     //move (2n+1) in ecx

        mov ebx, number  //move number in ebx
        add ebx, 1       //addition (n+1)
        jo end           //jump to end if overflow

        mov eax, number //move number in eax for multiplication
        mul ebx         //multiply n(n+1)
        jo end          //jump to end if overflow
        mul ecx         //multiply n(n+1)(2n+1)
        jo end          //jump to end if overflow
        mov ebx, 6      //move 6 in ebx
        div ebx         //divide by 6, the result will be in eax

        mov result, eax //move eax in result

end:
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

基本上,我想知道我可以在那里改进什么.在最佳实践方面.有一点听起来很明显:更智能的溢出检查(只需检查一下最大输入是否会导致溢出).

Dou*_*rie 8

    mov eax, number  //move number in eax
    mov ecx, eax     //dup in ecx
    mul ecx          //multiply (n*n)
    jo end           //jump to end if overflow
    add eax, ecx     //addition (n*n+n); can't overflow
    add ecx, ecx     //addition (2n); can't overflow
    add ecx, 1       //addition (2n+1); can't overflow
    mul ecx          //multiply (n*n+n)(2n+1)
    jo end           //jump to end if overflow
    mov ecx, 6       //move 6 in ebx
    div ecx          //divide by 6, the result will be in eax

    mov result, eax //move eax in result
Run Code Online (Sandbox Code Playgroud)

强度降低:增加而不是乘法.

通过分析,减少溢出检查(您可以按照您的描述做得更好).

将值保存在寄存器中而不是返回堆栈中的参数.

选择仔细注册,以便不会覆盖可重复使用的值.

  • 不能溢出因为n*n没有,所以n*n + n不会.n*n不会溢出的最大n是0xffff.0xffff*0xffff + 0xffff = 0xffff0000.由于此时n <= 0xffff,2n + 1最多为0x1ffff,同样没有溢出. (3认同)