菲林格尔地板价格表一览:分别用函数递归和非递归的方法求出两个整数的最大公约数。

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/01 17:18:34
要求必须是主函数中输入两个整数并输出最大公约数。
忘了说了 我是要C的,你写的是递归还是非递归的啊,我不懂的
种稻人,你的程序运行不了啊?

int a(int x,int y)
{
int temp;
temp=x%y;
if(temp==0)
{
return y;
}
else
{
return a(y,temp);
}
}
这个是递归的。刚才的楼上的那位先生是用的循环。

VB:
function k(m as integer,n as integer)
If m < n Then t = m: m = n: n = t
r=m mod n
Do While (r <> 0)
m=n
n=r
r= m mod n
Loop
Print "最大公约数=", n

C:
main()
{
int a,b,num1,num2,temp;
printf("please input two numbers:\n");
scanf("%d,%d",&num1,&num2);
if(num1
{ temp=num1;
num1=num2;
num2=temp;
}
a=num1;b=num2;
while(b!=0)/*利用辗除法,直到b为0为止*/
{
temp=a%b;
a=b;
b=temp;
}
printf("gongyueshu:%d\n",a);
}

一楼的有错误,我参考了一些资料,发布如下:

<1> 用辗转相除法求最大公约数(非递归)
算法描述:
m对n求余为a, 若a不等于0
则 m <- n, n <- a, 继续求余
否则 n 为最大公约数

#include <stdio.h>
int main()
{
int m, n;
int m_cup, n_cup, res; /*被除数, 除数, 余数*/
printf("Enter two integer:\n");
scanf("%d %d", &m, &n);
if (m > 0 && n >0)
{
m_cup = m;
n_cup = n;

res = m_cup % n_cup;
while (res != 0)
{
m_cup = n_cup;
n_cup = res;
res = m_cup % n_cup;
}

printf("Greatest common divisor: %d\n", n_cup);
}
else printf("Error!\n");
return 0;
}

<2> 用递归求最大公约数

#include <stdio.h>
int getGreatestCommonDivisor(int num1, int num2)
{
int temp;
temp = num1 % num2;
if (temp == 0)
{
return num2;
}
else
{
return getGreatestCommonDivisor(num2, temp);
}
}
int main()
{
int m, n;
int m_cup, n_cup, res; /*被除数, 除数, 余数*/
printf("Enter two integer:\n");
scanf("%d %d", &m, &n);
if (m > 0 && n >0)
{
m_cup = m;
n_cup = n;
printf("Greatest common divisor: %d\n", getGreatestCommonDivisor(m_cup, n_cup));
}
else printf("Error!\n");
return 0;
}