Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Recurring Cycle of Fractions

by Skeeve (Vicar)
on Sep 09, 2007 at 06:41 UTC ( #637889=note: print w/ replies, xml ) Need Help??


in reply to Recurring Cycle of Fractions

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


Comment on Re: Recurring Cycle of Fractions
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://637889]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (10)
As of 2014-12-28 14:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (181 votes), past polls