我已经知道小数在什么时候重复小数。这是功能。
public bool IsRepeatingDecimal { get { if (Numerator % Denominator == 0) return false; var primes = MathAlgorithms.Primes(Denominator); foreach (int n in primes) { if (n != 2 && n != 5) return true; } return false; } }
现在,我正在尝试获取重复的号码。我正在检查以下网站:http : //en.wikipedia.org/wiki/Repeating_decimal
public decimal RepeatingDecimal() { if (!IsRepeatingDecimal) throw new InvalidOperationException("The fraction is not producing repeating decimals"); int digitsToTake; switch (Denominator) { case 3: case 9: digitsToTake = 1; break; case 11: digitsToTake = 2; break; case 13: digitsToTake = 6; break; default: digitsToTake = Denominator - 1; break; } return MathExtensions.TruncateAt((decimal)Numerator / Denominator, digitsToTake); }
但是我确实意识到,有些数字具有部分十进制有限和后来的无限。例如:1/28
您知道更好的方法吗?还是算法?
一个非常简单的算法是:实现长除法。记录您所做的每个中间部门。一旦您看到与以前所做的相同的划分,就可以重复进行。
示例:7/13。
1. 13 goes into 7 0 times with remainder 7; bring down a 0. 2. 13 goes into 70 5 times with remainder 5; bring down a 0. 3. 13 goes into 50 3 times with remainder 11; bring down a 0. 4. 13 goes into 110 8 times with remainder 6; bring down a 0. 5. 13 goes into 60 4 times with remainder 8; bring down a 0. 6. 13 goes into 80 6 times with remainder 2; bring down a 0. 7. 13 goes into 20 1 time with remainder 7; bring down a 0. 8. We have already seen 13/70 on line 2; so lines 2-7 have the repeating part
该算法将538461作为重复部分。我的计算器说7/13是0.538461538。在我看来不错!剩下的只是实现细节,或者是寻找更好的算法!