In this assignment, you will implement a recursive solution for computing the GC
ID: 3775368 • Letter: I
Question
In this assignment, you will implement a recursive solution for computing the GCD of two positive integers. You may use the following C solution as a guide:
int gcd(int n1, int n2)
{
if (n2 != 0)
return gcd (n2, n1 % n2);
else
return n1;
}
Your main function will contain a loop that continuously checks for keyboard input in the following pattern:
<OPERAND_N1><ENTER>
<OPERAND_N2><ENTER>
Once the 2 lines of input are acquired, the operands should be loaded into the proper registers and the gcd procedure should be called. The procedure should return the result in register R0, and the main function should print “the gcd of n1 and n2 is x” (where n1, n2, and x are replaced with the proper numbers) and skip to a new line.
All input test cases will consist of positive numbers only. An example test case and its output is provided below:
100
40
The GCD of 100 and 40 is 20
1. Main function correctly retrieves 2 input parameters, prints result in a continuous loop (20 points) 2. gcd procedure implemented, registers R0, R1, R2 used as specified (30 points) 3. gcd procedure returns correct value in all cases (50 points)
Explanation / Answer
The Program :
#include <stdio.h>
#include <string.h>
register int n1,n2,result asm("R0");
int gcd(int n1, int n2)
int main(int argv, const char *argv[])
{
int i=0;
do{
scanf("%d ",argv[i]);
i++;
}while(i!=2)
n1= argv[0];
n2= argv[1];
result = gcd(n1,n2);
printf("The GCD of %d and %d is %d",n1,n2,result);
return 0;
}
int gcd(int n1,int n2)
{
if(n2!=0)
return gcd(n2,n1 % n2);
else
return n1;
}