Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Recurring Cycle of Fractions

by Limbic~Region (Chancellor)
on Sep 09, 2007 at 00:33 UTC ( #637880=perlquestion: print w/ replies, xml ) Need Help??
Limbic~Region has asked for the wisdom of the Perl Monks concerning the following question:

All,
This challenge was inspired from a Project Euler problem.

After converting a fraction into a floating point number, find the recurring cycle if there is one.

1/2 = 0.5 1/3 = 0.333333333333333333333 = 3 1/6 = 0.166666666666666666666 = 6 1/7 = 0.142857142857142857142 = 142857 1/9 = 0.111111111111111111111 = 1
This isn't a hard problem but I found it fun enough to share. Solve it any which way you want but bonus points for creativity. Since precision could be an issue, just assume that the provided string will be long enough for the recurring cycle to appear in its entirety at least twice. My solution is terribly inefficient and I will post it tomorrow.

Cheers - L~R

Comment on Recurring Cycle of Fractions
Download Code
Re: Recurring Cycle of Fractions
by Sidhekin (Priest) on Sep 09, 2007 at 01:34 UTC

    Actually, every rational number has a recurring cycle in a positional representation ... it's just that for some numbers it is a trivial "0" cycle. But that's just a quibble.

    Assuming that the provided string is long enough for two cycles to appear gets boring pretty quickly ... on my system that assumption fails already for 1/17, unless I use bignum. So I'll do that. And, true to habit, I'll use a regex to solve the problem. :)

    (Pass an argument to the program to get the cycle for the inverse of more (or less) than the default 99 first natural numbers:)

    #!/usr/bin/perl use strict; use warnings; use constant COUNT => $ARGV[0]||99; use constant LENGTH => length COUNT; use bignum a => 3*COUNT; # accuracy ... for my $n (1..COUNT) { my $f = substr(1/$n, 0, 3*COUNT); # precision too ... if ( $f =~ /(\d+?)\1+(?!\d{${\COUNT}})/ ) { # a little leeway ... printf " 1/%-*d = %-30.30s -> %s\n", LENGTH, $n, $f, $1; } else { # should never happen ... die "Insufficient precision/accuracy? Cannot handle the following +:\n$f\n"; } }

    Thank you — that was an interesting distraction. :)

    Update: Made the leeway big enough that we get the cycle sequence as it first appears, and not some arbitrary cycling of it, no matter how long the sequence.

    print "Just another Perl ${\(trickster and hacker)},"
    The Sidhekin proves Sidhe did it!

Re: Recurring Cycle of Fractions
by Skeeve (Vicar) on Sep 09, 2007 at 06:41 UTC
    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
Re: Recurring Cycle of Fractions (tiny)
by tye (Cardinal) on Sep 09, 2007 at 07:43 UTC

    Such boring limitations, as previously noted. But monstrously large floating points and regexes? Bah. It is simple enough to compute directly using boringly small integers:

    #!/usr/bin/perl -w use strict; my( $num, $den )= ( 1, 7, @ARGV )[2&@ARGV,-1]; my $rem= $num % $den; my %seen; my $rep= ''; while( 1 ) { $rem *= 10; last if exists $seen{$rem}; $seen{$rem}= length( $rep ); $rep .= int( $rem / $den ); $rem %= $den; } substr( $rep, 0, $seen{$rem} )= ''; print "$num / $den = ...$rep\n";

    Sample runs:

    $ perl repDig.pl 97 1 / 97 = ...010309278350515463917525773195876288659793 814432989690721649484536082474226804123711340206185567 $ perl repDig.pl 2 97 2 / 97 = ...020618556701030927835051546391752577319587 628865979381443298969072164948453608247422680412371134

    - tye        

      Same as mine but much shorter! ++!

      s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
      +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

        Oh wow, so it is. Sorry, I didn't look at your code since you didn't mention that you had gone outside the parameters provided so I didn't think that you had done what I was doing.

        In penance, here is a script that shows the repeat length for 1/$n only when that length isn't "boring". If $n is prime a repeat length of $n-1 is "boring". If $n is composite, the boring length is the max repeat length of its prime factors.

        #!/usr/bin/perl -w use strict; Main(); exit(); sub repDig { my( $den, $num )= @_; $num ||= 1; my $rem= $num % $den; my %seen; my $rep= ''; while( 1 ) { $rem *= 10; last if exists $seen{$rem}; $seen{$rem}= length( $rep ); $rep .= int( $rem / $den ); $rem %= $den; } substr( $rep, 0, $seen{$rem} )= ''; return $rep; } sub factor { my( $r )= @_; my $f= ''; my @f; my $p= 2; while( 1 < $r ) { my $q= int( $r / $p ); last if $q < $p; my $e= 0; while( $r == $q*$p && $q ) { $e++; $r= $q; $q= int( $r / $p ); } if( $e ) { push @f, $p; $f .= "*$p"; $f .= "^$e" if 1 < $e; } $p += 2==$p ? 1 : 2; } if( 1 < $r || ! @f ) { push @f, $r; $f .= "*$r"; } substr( $f, 0, 1 )= ''; return $f, @f; } sub Main { my $dem= 1; my %r; while( 1 ) { my( $f, @f )= factor( ++$dem ); my $r= repDig( $dem ); $r= $r ? length($r) : 0; if( $f eq $dem ) { $r{$dem}= $r; next if $r == $dem-1; } else { my $max= 0; for( @f ) { $max= $r{$_} if $max < $r{$_}; } next if $r == $max; } printf "%8d: 1/%s\n", $r, $f; } }

        and the first few lines of output:

        My favotite is: 42: 1/7^2

        Now demonstrate your understanding by correctly predicting a number with a repeat length of 11 or 25.

        - tye        

Re: Recurring Cycle of Fractions
by shmem (Canon) on Sep 09, 2007 at 17:32 UTC
    Am I missing something, or is a simple regex all that is needed?
    my @values = map { 1 / $_ } (2,3,6,7,9,11,13,14); for (@values) { /\.\d*?(\d+?)\1/; print "$_: $1\n" } __END__ 0.5: 0.333333333333333: 3 0.166666666666667: 6 0.142857142857143: 142857 0.111111111111111: 1 0.0909090909090909: 09 0.0769230769230769: 076923 0.0714285714285714: 714285

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
      You're missing oh so much... Try your attempt with 17 and 19...

      s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
      +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
        Try your attempt with 17 and 19...

        I do. Since there aren't enough digits, Math::BigFloat to the rescue:

        #!/usr/bin/perl use Math::BigFloat; Math::BigFloat->div_scale(50); my @values = map { my $i = Math::BigFloat->new( 1 ); scalar $i->bdiv( $_ ); } (2,3,6,7,9,11,13,14,17,19,23); for (@values) { /\.\d*?(\d+?)\1/; print "$_: $1\n" } __END__ 0.5: 0.33333333333333333333333333333333333333333333333333: 3 0.16666666666666666666666666666666666666666666666667: 6 0.14285714285714285714285714285714285714285714285714: 142857 0.11111111111111111111111111111111111111111111111111: 1 0.090909090909090909090909090909090909090909090909091: 09 0.076923076923076923076923076923076923076923076923077: 076923 0.071428571428571428571428571428571428571428571428571: 714285 0.058823529411764705882352941176470588235294117647059: 058823529411764 +7 0.052631578947368421052631578947368421052631578947368: 052631578947368 +421 0.043478260869565217391304347826086956521739130434783: 043478260869565 +2173913

        The regex is the same, though. Still missing something?

        update: Oh, I see. "try with 170..." :-)

        --shmem

        _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                      /\_¯/(q    /
        ----------------------------  \__(m.====·.(_("always off the crowd"))."·
        ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: Recurring Cycle of Fractions
by ikegami (Pope) on Sep 09, 2007 at 20:47 UTC
    /\.\d*?(\d+?)\1+(?!(??{ '.' x length($1) }))/
Re: Recurring Cycle of Fractions
by Limbic~Region (Chancellor) on Sep 09, 2007 at 20:56 UTC
    Al,
    As promised, here is my inefficient code as written specifically for the Euler problem.
    #!/usr/bin/perl use strict; use warnings; use Math::BigFloat; my ($max, $suspect) = (0,0); N: for (2..999) { my $n = Math::BigFloat->new(1); $n->bdiv($_, 4000); my ($str) = $n->bstr() =~ /(\d+)\1/; my ($best, $orig) = ('', $str); while (1) { my ($long_match) = $str =~ /(\d+)\1/; last if ! defined $long_match; next N if $long_match =~ /^(\d)\1+$/; # ensure we don't reduce too far my $len = length($long_match); my $mult = int(length($orig) / $len); last if substr($orig, 0, $len * $mult) !~ /^($long_match)+$/; $str = $best = $long_match; } my $len = length($best); ($max, $suspect) = ($len, $_) if $len > $max; } print "$max\t$suspect\n";

    Cheers - L~R

Re: Recurring Cycle of Fractions
by almut (Canon) on Sep 09, 2007 at 23:21 UTC

    Just for fun, here's another approach, based on the idea of XOR-ing the string with shifted versions of itself, to then extract the recurring substring from the case with the longest trailing "nulled-out" part. Hope you'll appreciate the creative aspect :) — even though it's not as compact as the regex approach suggested by ikegami.  Due to its generic approach, the algorithm should work not only with numbers, but with any kind of string.

    #!/usr/bin/perl my @vals; { # set up some high-precision fractions use constant PREC => 89; use bignum p => -(PREC); for my $num (2, 3, 6, 7, 14, 17, 23, 29, 47, 48, 49, 196, 197, 224, 467) { my $s = 1/$num; $s =~ s/0+$/0/; $s = substr($s, 0, PREC); push @vals, ["1/$num", $s]; } } while (<DATA>) { # add some non-numeric stuff, just as demo chomp; push @vals, ["", $_]; } for my $e (@vals) { my ($frac, $s) = @$e; my $ls = length $s; my $ss = $s; my $lmin = $ls; my $i = 0; my $n = 0; my $c = 0; while ($c++ < $ls) { last if $c > $lmin-$n; $ss = substr "\x01$ss",0,$ls; my $xor = $s ^ $ss; $xor =~ s/\0+$//; my $l = length $xor; if ($l < $lmin) { $lmin = $l; next if $l+$c > $ls; $i = $l-$c; $i = 0 if $i<0; $n = $c; } } printf "%-5s : %s", $frac, $s; printf "\n => %s%s", " "x$i, substr $s, $i, $n if $n; print "\n"; } __DATA__ also works with arbitrary strings: thisisjustblahblahblahb yadda, yadda, yadd

    prints:

    1/2 : 0.50 + 1/3 : 0.333333333333333333333333333333333333333333333333333333333333 +333333333333333333333333333 => 3 1/6 : 0.166666666666666666666666666666666666666666666666666666666666 +666666666666666666666666666 => 6 1/7 : 0.142857142857142857142857142857142857142857142857142857142857 +142857142857142857142857142 => 142857 1/14 : 0.071428571428571428571428571428571428571428571428571428571428 +571428571428571428571428571 => 714285 1/17 : 0.058823529411764705882352941176470588235294117647058823529411 +764705882352941176470588235 => 0588235294117647 1/23 : 0.043478260869565217391304347826086956521739130434782608695652 +173913043478260869565217391 => 0434782608695652173913 1/29 : 0.034482758620689655172413793103448275862068965517241379310344 +827586206896551724137931034 => 0344827586206896551724137931 1/47 : 0.021276595744680851063829787234042553191489361702127659574468 +085106382978723404255319148 1/48 : 0.020833333333333333333333333333333333333333333333333333333333 +333333333333333333333333333 => 3 1/49 : 0.020408163265306122448979591836734693877551020408163265306122 +448979591836734693877551020 => 020408163265306122448979591836734693877551 1/196 : 0.005102040816326530612244897959183673469387755102040816326530 +612244897959183673469387755 => 510204081632653061224489795918367346938775 1/197 : 0.005076142131979695431472081218274111675126903553299492385786 +802030456852791878172588832 1/224 : 0.004464285714285714285714285714285714285714285714285714285714 +285714285714285714285714285 => 428571 1/467 : 0.002141327623126338329764453961456102783725910064239828693790 +149892933618843683083511777 => + 7 : also works with arbitrary strings: + : thisisjustblahblahblahb + => blah : yadda, yadda, yadd + => yadda,

    BTW, I'll admit it up-front: in its current version, this algorithm has a subtle problem. As you can see when looking at the last number (1/467), it falsely reports '7' as the recurring part, as a result of the number being cut off prematurely due to insufficient precision... (a problem it shares with the regex solution, btw). Presumably some heuristic workaround can be found for that, but I'll leave this as an 'exercise for the reader'... ;)

Re: Recurring Cycle of Fractions
by ambrus (Abbot) on Sep 10, 2007 at 07:02 UTC
Re: Recurring Cycle of Fractions
by steph (Initiate) on Oct 18, 2012 at 14:17 UTC
    There you go
    #!/usr/bin/perl use strict; use warnings; use bignum ( p => -9999 ); # this is huge, by the way my $limit = shift; # 1000 for project euler my $longest = 1; my $value; for my $val (1..$limit) { my $frac = 1/$val; if (reverse($frac) =~ /(\d+)\1+/) { my $longestSubChain = reverse($1); if ($longestSubChain =~ /(\d+?)\1+/) { if (length($1) > $longest) { $longest = length +($1); $value = $val; } } } } print "d = $value\n"; print "Longest recurring cycle: $longest";

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://637880]
Approved by graff
Front-paged by Old_Gray_Bear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (10)
As of 2014-08-28 08:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (257 votes), past polls