首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >大脑中的乘法

大脑中的乘法
EN

Stack Overflow用户
提问于 2016-12-07 08:17:59
回答 2查看 702关注 0票数 0

我试图编写一个brainfuck程序,它要求用户使用两个数字(小于10)来计算这些数字的乘积。计算完毕后,应打印结果。我的代码如下所示:

代码语言:javascript
运行
复制
    ++++[>++++[>+++<-]<-]   writing 48 / 0x30 / '0' in cell(2)
    ,>,>                    reading two numbers in cell(0) and cell(1)
    [<-<->>-]               decrementing cell(0) and cell(1) by 48 / 0x30 / '0'
    <<                      go to cell(0)
    [                       muliplication loop
        >                   go to cell(1)
        [>+>+<<-]           move cell(1) to cell(2) and cell(3)
        >>                  go to cell(3)
        [<<+>>-]            move cell(3) back to cell(1)
        <<<-                decrement cell(0)
    ]
    ++++[>++++[>+++<-]<-]   adding 48 / 0x30 / '0' to cell(2)
    >>.                     print result

这给了我非常奇怪的结果:

代码语言:javascript
运行
复制
0 * 1 = 3
1 * 1 = 4
1 * 2 = 8
2 * 1 = 5
2 * 2 = :

诸若此类。

当然,输出实际上如下所示:

代码语言:javascript
运行
复制
1
1
4

但我想在这里展示它的可读性。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-07 08:17:59

经过一番考虑后,我意识到,当我把结果修改成一个可打印的数字时,我犯了很大的错误。我使用单元格(1)作为临时计数器单元格,尽管它在其中仍然有价值。因此,在向结果添加>[-]<之前,我插入了48 / 0x30 / '0'

代码语言:javascript
运行
复制
    ++++[>++++[>+++<-]<-]   writing 48 / 0x30 / '0' in cell(2)
    ,>,>                    reading two numbers in cell(0) and cell(1)
    [<-<->>-]               decrementing cell(0) and cell(1) by 48 / 0x30 / '0'
    <<                      go to cell(0)
    [                       mulitplication loop
        >                   go to cell(1)
        [>+>+<<-]           move cell(1) to cell(2) and cell(3)
        >>                  go to cell(3)
        [<<+>>-]            move cell(3) back to cell(1)
        <<<-                decrement cell(0)
    ]
    >[-]<                   set cell(1) to 0 so that it can be used as counter
    ++++[>++++[>+++<-]<-]   adding 48 / 0x30 / '0' to cell(2)
    >>.                     print result

注意,它仍然只在小于10的结果中正确工作。

票数 1
EN

Stack Overflow用户

发布于 2016-12-12 00:31:23

Brainfuck算法的Esolangs页面是一个非常好的资源。在那里,乘法被定义为:

代码语言:javascript
运行
复制
temp0[-]
temp1[-]
x[temp1+x-]
temp1[
 y[x+temp0+y-]temp0[y+temp0-]
temp1-]

因此,如果磁带看起来一般类似于temp0 temp1 x y,指针位于temp0,那么结果将是:

代码语言:javascript
运行
复制
[-]
>[-]
>[<+>-]
<[
 >>[<+<<+>>>-]<<<[>>>+<<<-]
>-]

但是,在调用.输出时会出现主要问题。您的方法只在输出个位数时起作用。要将单元格的内容输出为数字,可以使用以下代码:

代码语言:javascript
运行
复制
>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-
<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++++++
<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]

(包含此算法的原始帖子。)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41012415

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档