貪心法——埃及分數

問題

在這裏插入圖片描述

代碼

/*
* problem: 埃及分數
* method: 貪心法
* date: 2020/05/11
*/
#include<iostream>
using namespace std;
int CommFactor(int a,int b) {
 int c=b;
 while(a%b){
  c=a%b;
  a=b;
  b=c;
 }
 return c;
}
void EgyptFactor(int a,int b) {
 int e,r;
 while(a>1) {
  e=b/a+1;
  cout<<"1/"<<e<<"+";
  a=a*e-b;
  b=b*e;
  r=CommFactor(a,b);
  if(r>1){
   a/=r;
   b/=r;
  }
 }
 cout<<"1/"<<b<<endl;
}
int main() {
 EgyptFactor(7,8);
 return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章