Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Recurring Cycle of Fractions

by Sidhekin (Priest)
on Sep 09, 2007 at 01:34 UTC ( #637884=note: print w/replies, xml ) Need Help??


in reply to Recurring Cycle of Fractions

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!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://637884]
help
Chatterbox?
[Corion]: karlgoethebier: Heh - naah, I think they are just very fresh out of university. At least they seem to have hired one person as key accountant who has done enterprise consulting etc. before :)
[Corion]: erix: It wouldn't be nice of me to publically shame and name ;)
[Corion]: I'm interested in how their product actually works. It uses websockets between two non-browser components, so there are some weird technology decisions, or rather, I assume the product started out as something completely different :)
[erix]: fair enough

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2018-04-19 12:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?