Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

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; }
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


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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2015-11-26 20:38 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (707 votes), past polls