【求助】一个求所有公约数的问题
问题:用下面给定的代码调用,实现函数 int CommonFactors( int a , int b ),计算a和b的所有公约数。第一次调用,返回最大公约数。以后只要再使用相同参数调用,每次返回下一个小一些的公约数。无公约数时返回 -1。
小弟的程序如下:
#include <stdio.h>
#include <conio.h>
/********* 该函数用于求两个数的最大公约数 ***************/
int MaxCommonFactor( int a , int b )
{
int temp;
if( a == b )
return a;
else
if( a > b )
haha:while(a> b)
{
a = a-b;
if( a == b )
return a;
if( a < b )
goto houhou;
}
else
if( b > a )
houhou:while(b> a)
{
b = b-a;
if( b == a )
return b;
if( b < a )
goto haha;
}
}
/*********该函数用与求某个数的全部约数***********/
int CommonFactors( int a , int b )
{
int maxCommonFactor ;
static i;
maxCommonFactor = MaxCommonFactor( a , b );
for( i = maxCommonFactor ; i > = 1 ; i-- )
if( maxCommonFactor%i == 0)
return ( i );
}
/********* 以下是主函数 ***********/
void main( )
{
int sub,a,b;
char flag;
printf( " According this program,you can get all the commonfactors of two numbers.\n\n " );
printf( "Please enpower a ,b : " );
scanf( "%d %d ",&a,&b );
do
{
while( sub = CommonFactors( a,b ) > 0 );
{
static int counter=1;
printf( " Common factor %d is %d \n ", counter++,sub );
}
printf( "Press button 'g ' or 'G ' to contiue : ");
flag = getche();
printf( "\n\n " );
} while( flag == 'g ' || flag == 'G ' );
system( "pause " );
}
抛开“无公约数时返回 -1”不讲。我的这个程序不能得出结果,从cpu的利用情况来看,可能是死循环了(吼一吼,也有可能有其他情况啊,可是……我不知道啊~)。
PS:那个求最大公约数的程序虽然用了两个goto,但我保证是对的。
[解决办法]
/* 标准文档模板 */
#include "Stdio.h "
#include "Conio.h "
int main(void)
{
int c1,c2,temp,i,number;
c1=18;
c2=4;
number=0;
if(c1 <c2)
{
temp=c1;
c1=c2;
c2=temp;
}
for(i=2;i <=c2;i++)
{
if((c1%i==0)&&(c2%i==0))
{
printf( "%d ",i);
++number;
}
}
if(number==0)
printf( "%d and %d 无最大公约数 ",c1,c2);
getch();
return 0;
}