Here is my (fixed) simple solution. The output is slightly different in that it puts a "p" before the start of the periode.
#!/usr/bin/perl
use strict;
use warnings;
divide(1,18);
for (my $i=1; $i<20; ++$i) {
print "1/",$i,"=",divide(1,$i),"\n";
}
sub divide {
my ($z,$n)= @_;
my (
%rec,
$rem,
$res,
);
my $dig= '';
$res= int($z/$n);
$z-= $res*$n;
while ($z) {
$z*=10;
$rem= $z % $n;
$dig.= int($z/$n);
if (defined $rec{$rem}) {
my $p= $rec{$rem};
if ($p>0 and substr($dig,$p-1,1) eq substr($dig,-1)) {
substr($dig,-1,1)='';
--$p;
}
return $res. "." . substr($dig,0,$p)."p".substr($dig,$p);
}
$rec{$rem}= length($dig);
$z= $rem;
}
return $res . "." . $dig;
}
output:
1/1=1.
1/2=0.5
1/3=0.p3
1/4=0.25
1/5=0.2
1/6=0.1p6
1/7=0.p142857
1/8=0.125
1/9=0.p1
1/10=0.1
1/11=0.p09
1/12=0.08p3
1/13=0.p076923
1/14=0.0p714285
1/15=0.0p6
1/16=0.0625
1/17=0.p0588235294117647
1/18=0.0p5
1/19=0.p052631578947368421
s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
+.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.