Integer long division: Difference between revisions
Content added Content deleted
(Added Wren) |
|||
Line 41: | Line 41: | ||
00067114093959731543624161073825503355704697986577181208053691275167785234899328859060402684563758389261744966442953020134228187919463087248322147651 |
00067114093959731543624161073825503355704697986577181208053691275167785234899328859060402684563758389261744966442953020134228187919463087248322147651 |
||
148 |
148 |
||
</pre> |
|||
=={{header|Wren}}== |
|||
This is based on the Python code [http://codepad.org/hKboFPd2 here]. |
|||
<lang ecmascript>var divide = Fn.new { |m, n| |
|||
if (m < 0) Fiber.abort("m must not be negative") |
|||
if (n <= 0) Fiber.abort("n must be positive.") |
|||
var quotient = (m/n).floor.toString + "." |
|||
var c = 10 * (m % n) |
|||
var zeros = 0 |
|||
while (c > 0 && c < n) { |
|||
c = c * 10 |
|||
quotient = quotient + "0" |
|||
zeros = zeros + 1 |
|||
} |
|||
var digits = "" |
|||
var passed = {} |
|||
var i = 0 |
|||
while (true) { |
|||
if (passed.containsKey(c)) { |
|||
var prefix = digits[0...passed[c]] |
|||
var cycle = digits[passed[c]..-1] |
|||
var result = quotient + prefix + "(" + cycle + ")" |
|||
result = result.replace("(0)", "").trimEnd(".") |
|||
var index = result.indexOf("(") |
|||
if (index == -1) return [result, "", 0] |
|||
var repetend = result[index+1..-2] |
|||
var period = result.count - index - 2 |
|||
result = result.replace("(", "").replace(")", "") |
|||
for (i in 0...zeros) { |
|||
if (repetend[-1] == "0") { |
|||
result = result[0..-2] |
|||
repetend = "0" + repetend[0..-2] |
|||
} else break |
|||
} |
|||
return [result + "....", repetend, period] |
|||
} |
|||
var q = (c / n).floor |
|||
var r = c % n |
|||
passed[c] = i |
|||
digits = digits + q.toString |
|||
i = i + 1 |
|||
c = 10 * r |
|||
} |
|||
} |
|||
var tests = [ [1, 1], [1, 3], [1, 7], [1, 17], [10, 13], [3227, 555], [1, 149] ] |
|||
for (test in tests) { |
|||
var a = test[0] |
|||
var b = test[1] |
|||
var res = divide.call(a, b) |
|||
System.print("%(a)/%(b) = %(res[0])") |
|||
System.print("Repetend is '%(res[1])'") |
|||
System.print("Period is %(res[2])\n") |
|||
}</lang> |
|||
{{out}} |
|||
<pre> |
|||
1/1 = 1 |
|||
Repetend is '' |
|||
Period is 0 |
|||
1/3 = 0.3.... |
|||
Repetend is '3' |
|||
Period is 1 |
|||
1/7 = 0.142857.... |
|||
Repetend is '142857' |
|||
Period is 6 |
|||
1/17 = 0.0588235294117647.... |
|||
Repetend is '0588235294117647' |
|||
Period is 16 |
|||
10/13 = 0.769230.... |
|||
Repetend is '769230' |
|||
Period is 6 |
|||
3227/555 = 5.8144.... |
|||
Repetend is '144' |
|||
Period is 3 |
|||
1/149 = 0.0067114093959731543624161073825503355704697986577181208053691275167785234899328859060402684563758389261744966442953020134228187919463087248322147651.... |
|||
Repetend is '0067114093959731543624161073825503355704697986577181208053691275167785234899328859060402684563758389261744966442953020134228187919463087248322147651' |
|||
Period is 148 |
|||
</pre> |
</pre> |