当前位置: 代码迷 >> 综合 >> 辗转相除法求公因数公倍数
  详细解决方案

辗转相除法求公因数公倍数

热度:30   发布时间:2024-02-13 09:54:21.0

 

 

#include <bits/stdc++.h>
using namespace std;//公因数
int gcd(int a, int b)
{int da = max(a,b);int xiao = min(a,b);if(da % xiao == 0)return xiao;elsereturn gcd(xiao, da % xiao);}
// 两个整数的最小公倍数等于两整数之积除以最大公约数int lcm(int a, int b)
{return a*b / gcd(a, b);
}int main()
{int a,b,c,d;char fan;scanf("%d/%d %c %d/%d",&a,&b,&fan,&c,&d);int firsta=a*d,firstb=c*d;int second=b*d;int first;if(fan=='+'){first=firsta+firstb;}if(fan=='-'){first=firsta-firstb;}if(fan=='*'){first=a*c;}if(first<0){printf("-");first=-first;}if(first==second){printf("1");}else{if(first>second){cout<<first/second;first%=second;}int temp=gcd(first,second);first/=temp;second/=temp;printf("%d/%d",first,second);}return 0;
}

 

  相关解决方案