求两个整数的最大公约数

来源:互联网 发布:起名软件免费 编辑:程序博客网 时间:2024/05/29 02:49

题目:从键盘输入两个整数,输出两个整数的最大公约数。用C或C++语言实现程序解决问题。(三种方法解决)

/*穷举法*/#include<stdio.h>void main(){    int temp=0,a,b;    printf("请输入要求最大公约数的两个数:\n");    scanf("%d %d",&a,&b);    if(a<b){   //保证a>b        a=a^b; //用异或法交换a,b的值        b=a^b;        a=a^b;    }    for(temp=b;;temp--){  //用穷举法求最大公约数        if(a%temp==0&&b%temp==0)            break;    }    printf("最大公约数为:%d\n",temp);}
/*辗转相除法*/#include<stdio.h>void main(){    void count(int,int);    int a,b,*p1,*p2;    printf("请输入要求最大公约数的两个整数:\n");    scanf("%d %d",&a,&b);    p1=&a;    p2=&b;    if(a>b){            count(a,b);            }else            count(b,a);             }//求最大公约数的函数void count(int a,int b){    void swap(int*,int*); //声明交换两数的方法    int c=0;    do{        c=a%b;        swap(&b,&c);        }while(b>0);        printf("两数的最大公约数为:");        printf("%d\n",c); }//用指针交换两个数void swap(int* i,int* j){    int temp;    temp=*i;    *i=*j;    *j=temp;} 
/*辗转相减法*/#include<stdio.h>void main(){    void count(int,int);    int a,b;    printf("请输入要求最大公约数的两个整数:\n");    scanf("%d %d",&a,&b);    if(a>b){            count(a,b);        }else count(b,a);                       }//求最大公约数的函数void count(int a,int b){    int c;    do{        c=a-b;         a=a+b;  //用两数之和法交换a,b的值        b=a-b;        a=a-b;        b=c;       }while(b!=c);        printf("两数的最大公约数为:");        printf("%d\n",c);}
1 0
原创粉丝点击