1092 計算機組織與組合語言
題目說明 In this assignment, you are asked to write a MIPS recursive program that computes the greatest common divisor (GCD, 最大公因數) of two given positive integers.
環境設定 MARS MIPS simulator
參考解法 MIPS 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 .text main: li $v0 , 5 syscall move $a0 , $v0 li $v0 , 5 syscall move $a1 , $v0 GCD1: addi $sp , $sp , -12 sw $ra , 8 ($sp ) sw $a0 , 4 ($sp ) sw $a1 , 0 ($sp ) bne $a1 , $0 , GCD2 add $v0 , $a0 , $0 li $v0 ,1 syscall j exitGCD2: div $a0 , $a1 mfhi $t0 move $a0 , $a1 move $a1 , $t0 jal GCD1 lw $a1 , 0 ($sp ) lw $a0 , 4 ($sp ) lw $ra , 8 ($sp ) addi $sp , $sp , 12 move $v0 , $a0 jr $ra exit:
C++ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 #include <iostream> using namespace std;int integer, sum = 0 ;int answer[100 ] = {};int gcd (int num1, int num2) ;int gcd (int num1, int num2) { if (num2 == 0 ) { return num1; } else { return gcd (num2, num1 % num2); } } int main () { cin >> integer; while (integer != 0 ) { if (integer == 0 ) { system ("pause" ); } else { for (int i = 1 ; i < integer; i++) { for (int j = 1 + i; j <= integer; j++) { sum += gcd (i, j); } } cout << sum << endl; sum = 0 ; } integer = 0 ; cin >> integer; } }