码迷,mamicode.com
首页 > 其他好文 > 详细

辗转相除法求最大公约数,非goto

时间:2014-12-01 20:43:00      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   sp   for   on   div   

 1 #include<iostream>
 2 using namespace std;
 3 //不推荐用goto,当然用它更快
 4 //辗转相除法求两数的最大公约数
 5 int gcd(long int a,long int b){
 6     int x=a<b?a:b;
 7     //获得较小者,用来做循环的约束值
 8     
 9     for(int i=0;i<x;x++){
10         //循环
11       if(a>b){
12           int r=a%b;//取余数
13           if(r==0){//能否整除判断
14              return b;//可以便输出
15           }else{//否则进行下一轮的算法
16               a=b,b=r;
17           }
18       }else if(a<b){//下面一样
19           int r=b%a;
20           if(r==0){
21               return a;
22           }else{
23               b=a,a=r;
24           }
25       }else{//两数相等的,直接输出其中一个
26           return a;
27       }
28    }
29 }
30 
31 int main(){
32     int y=0;y=gcd(156,176);
33     cout<<"156和176的最大公约数是:"<<y;
34 
35     return 0;
36 }

 

辗转相除法求最大公约数,非goto

标签:style   blog   io   color   os   sp   for   on   div   

原文地址:http://www.cnblogs.com/linguanh/p/4135880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!