我在做一个项目,但我被困住了。我试图编写一个代码片段,检查给定的数字是否甚至减去2(给定的数字不能超过6)。如果它是偶数,它打印一个0,如果它是奇数,它打印一个1。
int count=input.nextInt()
int parity=0
while (count>0)
count=count-2;
if (count<0) {
parity=parity+1;
System.out.print(parity);
}
else if (count==0) {
System.out.println(parity);
}^^这是我的java代码,我试着把它翻译成MARIE语言,但是没有任何效果。
我会发我的MARIE代码,但我觉得太让人困惑了
发布于 2018-03-13 06:23:10
您只需要检查0/非零的低位。普通的体系结构有一个和指令,这会使它变得简单,但是玛丽只有加法/分 (并比较大于或小于)。
但是是的,您的循环将工作,对一个数字n进行O(n)迭代。如果您将它写成一个do{}while()循环,那么在asm中实现它就容易多了,如
n = input;
do {
n-=2; // sub
}while(n>=0); // skipcond
// n==0 or -1 for even or odd您可以在O(log(n))操作中使用add作为左移位:AC+AC与AC << 1相同。这样做15次,将低位移至顶部,而其他位移出。(累加器,交流,有16位宽)。
不幸的是,这对玛丽来说真的很不方便,因为仅用于内存源操作数。,而不是AC。因此,您必须将AC存储在某个地方,以便可以将其用作添加的内存源操作数。
(当您知道您的输入在0.6范围内时,这是绝对不值得的。在这种情况下,n-=2循环最多只需要3次迭代就可以得到结果,而通常只有15次。但是如果输入不受限制,n-=2版本可能需要32768次迭代!或者16384,如果我们把它限制在正负号整数上;n-=2版本甚至不适用于负整数)
例如:
/ Assuming input in AC
Store tmp
Add tmp
Store tmp
Add tmp
/ repeat this 13 more times, for a total of 15 ADDs
/ inconvenient to make a loop because Marie only has 1 register
/ but would be smaller for this many shifts
/ AC = input << 15
/ AC is non-zero for odd, zero for even. You could just store that directly if you want.
/ If you want to branch on it here, or in some code that reloads that 0 / non-zero result
SkipCond 400 / jump over next insn if AC==0
jump odd_input / or this can be a store instruction
/ else fall through when input was even: input&1 == 0
tmp, dec 0循环是有意义的,特别是当你用2或什么展开它的时候。如果AC只有8位,那么完全展开只需要7个存储/添加指令,但是15是有点多。
https://stackoverflow.com/questions/49249141
复制相似问题