日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

5kyu Some Egyptian fractions

發布時間:2025/3/21 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 5kyu Some Egyptian fractions 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

5kyu Some Egyptian fractions

題目背景:

Given a rational number n

as a string (example: “2/3” in Ruby, Python, Clojure, JS, CS, Go) or as two strings (example: “2” “3” in Haskell, Java, CSharp, C++, Swift) decompose this number as a sum of rationals with numerators equal to one and without repetitions (2/3 = 1/2 + 1/6 is correct but not 2/3 = 1/3 + 1/3, 1/3 is repeated).

The algorithm must be “greedy”, so at each stage the new rational obtained in the decomposition must have a denominator as small as possible. In this manner the sum of a few fractions in the decomposition gives a rather good approximation of the rational to decompose.

2/3 = 1/3 + 1/3 doesn’t fit because of the repetition but also because the first 1/3 has a denominator bigger than the one in 1/2 in the decomposition 2/3 = 1/2 + 1/6.

題目分析:

埃及分數是很有趣的一個數字的性質,本道題本質上是數學上的問題分析,對于大于1的部分,直接分子除以分母獲取大于1的那部分整數即可;對于拆解出的小于1的部分,如果分母可以整除了分子,那么說明埃及分數的迭代結束,而倘若不能夠整除,需要用到貪心思想,去找到最小的分母,譬如 6 / 14, 那么它可以生成的數里面,最小的分母是 14 / 6 (c++中int 除以 int會下取整得到int型結果 ) + 1 = 3 ,于是6 / 14 = 1 / 3 + ((3 * 6) - 14) / (3 * 14) = 1 / 3 + 4 / 42 ,按照這個思路就可以寫出整個程序。

AC代碼:

using namespace std;class Decomp{ public:static string decompose(const string &nrStr, const string &drStr); };string Decomp::decompose(const string &nrStr, const string &drStr){long nr = std::stol(nrStr);long dr = std::stol(drStr);if ( nr == 0 || dr == 0 ) return "[]";string res = "[";while ( nr != 0 && dr != 0 ) {if ( nr >= dr ) {res += std::to_string(nr / dr);nr -= (nr / dr) * dr;}else {res += "1/";long tmp;if ( dr % nr == 0 ) tmp = dr / nr;else tmp = dr / nr + 1;res += std::to_string(tmp);nr = nr * tmp - dr;dr = dr * tmp;}res += ", ";}res = res.substr(0, res.size() - 2) + "]";return res; }

總結

以上是生活随笔為你收集整理的5kyu Some Egyptian fractions的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。