輾轉相除法求最大公約數

來源:互聯網
上載者:User

標籤:include   遞迴   實現   oid   class   ret   公約數   return   while   

 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     else23         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\n%d\n",z,z2);34     return 0;35 }

 

輾轉相除法求最大公約數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.