zoukankan      html  css  js  c++  java
  • 辗转相除法求最大公约数

     1 #include<stdio.h>
     2 void sort(int *pa,int *pb){//a,b按照从大到小的次序排列(利用了指针,实现“双向”传递)
     3     int t;
     4     if(*pa<*pb){
     5         t=*pa;*pa=*pb;*pb=t;
     6     }
     7 }
     8 int gcd_1(int a,int b){//用辗转相除法求最大公约数
     9     int c;
    10     if(b!=0){
    11         while(a%b!=0){
    12             c=b;
    13             b=a%b;
    14             a=c;
    15         }
    16     }
    17     return b;
    18 }
    19 int gcd_2(int a,int b){//辗转相除法的递归写法
    20     int c;
    21     if(b==0)c=a;
    22     else
    23         c=gcd_2(b,a%b);
    24     return c;
    25 }
    26 int main(){
    27     int x,y,z,z2,*pa,*pb;
    28     scanf("%d%d",&x,&y);
    29     pa=&x,pb=&y;         //若此处改为*pa=x,*pb=y;则pa、pb为野指针
    30     sort(pa,pb);
    31     z=gcd_1(x,y);
    32     z2=gcd_2(x,y);
    33     printf("%d
    %d
    ",z,z2);
    34     return 0;
    35 }
  • 相关阅读:
    HDU 5521 Meeting
    HDU 5170 GTY's math problem
    HDU 5531 Rebuild
    HDU 5534 Partial Tree
    HDU 4101 Ali and Baba
    HDU 5522 Numbers
    HDU 5523 Game
    ZUFE OJ 2301 GW I (3)
    POJ 2398 Toy Storage
    POJ 2318 TOYS
  • 原文地址:https://www.cnblogs.com/luzhiliang/p/6217322.html
Copyright © 2011-2022 走看看