x86汇编的collat​​z猜想中的细分错误

问题描述

我正在尝试编写一个子程序,该子程序接受一个正整数,并通过遵循Collat​​z猜想返回该整数达到1所需的步数。如果输入为1,则输出应为零。

我的伪代码是递归的(我们只能使用递归)

int threexplusone(int x){
    if(x == 1){
      return 0;
    }else{
      if(x % 2 == 0){
        return (threexplusone(x/2)+1);
      }else{
        return (threexplusone(3*x+1)+1);
      }
    }
}

我的代码就是这样

threexplusone:
    push rbx        ;store the rbx to stack
    mov rax,0      ;store the base case
    cmp rdi,1      ;compare the input with 1
    je done         ;finished the loop if equal to 1
    jmp threexplusone_recursive ;jump to the recursion

threexplusone_recursive:
    mov rbx,rdi        ;move rdi's value to rbx
    sar rbx,1      ;divide x by 2
    sub rbx,rdi        ;substitute to get the remainder
    cmp rbx,0      ;compare to check if the remainder is 0
    je  even        ;start the even instruction
    jne odd         ;start the odd insturction

even:
    sar rdi,1       ;divided the input by 2
    xor rax,rax
    call threexplusone  ;do the recursion

    inc rax         ;add the result by one
    jmp done        ;

odd:
    imul rdi,3      ;multiply x by 3
    add rdi,1      ;add x by 1
    xor rax,rax
    call threexplusone  ;do the recursion
        
    inc rax     ;add the result by one
    jmp done        ;

done:
    pop rbx
    ret

我正在cpp文件中对其进行测试,

1。询问输入值x,它是要传递给子例程的正整数,

2。询问输入值n,它是调用子例程的次数

3。运行一次子例程并存储结果

4。使用参数x作为输入运行子程序n次

5。打印出整数收敛到1所需的迭代次数。

int main(){
    int x;
    cout << "Enter a number: " << endl;
    cin >> x;
    int n; 
    cout << "Enter iterations of subroutine: " << endl;
    cin >> n;
    int result = threexplusone(x);
    for(int i = 0; i < n; i++){
        result = threexplusone(x);
    }
    cout << result << endl;
    
    return 0;
}

预期结果应该是

Enter a number: 
100
Enter iterations of subroutine: 
30
Steps take: 25

Insetead,我遇到了段错误

Enter a number: 
100
Enter iterations of subroutine: 
30
Segmentation fault (core dumped)

我一步步调试一下,这就是告诉我的

Program received signal SIGSEGV,Segmentation fault.
0x000000000040133a in odd ()

所以问题似乎出在奇巧的部分

odd:
    imul rdi,rax
    call threexplusone  ;do the recursion
        
    inc rax     ;add the result by one
    jmp done    

我想知道程序集的哪一部分可能是原因?谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...