C_Euclidean algorithm

17 篇文章 0 订阅
16 篇文章 0 订阅

最简分式(10分)
题目内容:

分数可以表示为“分子/分母”的形式。编写一个程序,要求用户输入一个分数,然后将其约分为最简分式。最简分式是指分子和分母不具有可以约分的成分了。如6/12可以被约分为1/2。当分子大于分母时,不需要表达为整数又分数的形式,即11/8还是11/8;而当分子分母相等时,仍然表达为1/1的分数形式。

输入格式:

输入在一行中给出一个分数,分子和分母中间以斜杠“/”分隔,如: 12/34 表示34分之12。分子和分母都是正整数(不包含0)。

提示:在scnaf的格式字符串中加入“/”。

输出格式:

在一行中输出这个分数对应的最简分式,格式与输入的相同,即采用“分子/分母”的形式表示分数。如 5/6 表示 6分之5

输入样例:

60/120

输出样例:

1/2

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int gcd(int a, int b){
	//Euclidean algorithm figure out the common divisor
	//120/21 -->5..15
	//21/15-->1..6
	//15/6-->2..3
	//6/3-->2..0
	//3

	//8/11-->0..8
	//11/8-->1..3
	//8/3-->2..2
	//3/2-->1..1
	//2/1-->2..0
	//1/0 -->return 1(a)

	//120/20-->6..0
	int rem=1;
	while(b){
		//while(rem&&b){ 
		//for test --> equals (rem!=0&&b!=0)
		rem=a%b;
		a=b;
		b=rem;
	}
	return a;
}
int main(){
	//12/24-->1/2
	//12/6 --> 2/1
	//11/8-->11/8
	int rem,a,b;
	scanf("%d/%d",&a,&b);
	rem=gcd(a,b);//remainder of a and b(1/not)
	if(rem!=1){
		printf("%d/%d",a/rem,b/rem);
	}
	else{
		printf("%d/%d",a,b);
	}
}

Euclidean algorithm

base on principal : gcd(a, b) = gcd(b, a mod b)

//recursion realization
int GCD(int a,int b){
     return b==0?a:GCD(b,a%b);
     }
//circulation realization
int gcd(int a, int b){
	int rem=1;
	while(b){
		rem=a%b;
		a=b;
		b=rem;
	}
	return a;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值