Assembly 如何使用MARIE查找偶数?
我正在做一个项目,但我被卡住了。我试图编写一段代码,通过将给定的数字减去2(给定的数字不能超过6)来检查给定的数字是否为偶数。如果是偶数,则打印0,如果是奇数,则打印1Assembly 如何使用MARIE查找偶数?,assembly,marie,Assembly,Marie,我正在做一个项目,但我被卡住了。我试图编写一段代码,通过将给定的数字减去2(给定的数字不能超过6)来检查给定的数字是否为偶数。如果是偶数,则打印0,如果是奇数,则打印1 int count=input.nextInt() int parity=0 while (count>0) count=count-2; if (count<0) { parity=parity+1; Syst
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);
}
int count=input.nextInt()
整数奇偶校验=0
而(计数>0)
计数=计数-2;
if(count您只需要检查低位是否为0/非零。正常的体系结构有一个AND指令,可以使这变得简单,但是(比较大于或小于)
但是,是的,您的循环将工作,对一个数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是一样的。通常,您应该发布asm代码,并用注释标记它,说明您知道哪些部件不起作用,并用注释说明部件应该如何工作(包括您认为正确的零件。)如果你不展示你的尝试,我们就不能给你一个非常具体的答案。虽然在这种情况下很容易理解为什么从混乱的Java开始会很困难!循环中有这么多条件。有更有效的方法来确定一个数是否为偶数…例如,测试最低阶位是否为零。谢谢!我是able想以此为基础,完成我的循环
/ 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