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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.