Perl-Sensitive Sunglasses PerlMonks

### Re^2: Determining if a rational number terminates

by tobyink (Abbot)
 on Nov 29, 2012 at 16:52 UTC ( #1006301=note: print w/replies, xml ) Need Help??

There are probably shorter ways of doing it, but...

```# It is important to clearly comment your code to make it easier
# for future maintainers.
#

# This is the numerator, denominator pair for which we wish to
# determine if the decimal expansion terminates.
#
@ARGV = (33, 660);

# Check if it terminates and print "Y" or "N".
#
sub _{@i=sort{\$b-\$a}@_;return\$i[1]if\$i[0]==\$i[1];@i=(\$i[1],\$i[0]%\$i
[1])while\$i[1];\$i[0]};sub __{\$j=_@_;\$_/=\$j for@_;\$_[1]<0and do{\$_*=
-1for@_}}__((\$k,\$l)=@ARGV);\$l/=2until\$l%2;print\$l=~/(5|^1)\$/?Y:N,\$/
perl -E'sub Monkey::do{say\$_,for@_,do{(\$monkey=[caller(0)]->[3])=~s{::}{ }and\$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re^3: Determining if a rational number terminates
by blackle (Beadle) on Nov 29, 2012 at 18:12 UTC

Thanks for that, I didn't even consider that it wouldn't be in lowest form.

It's really clever to take advantage of the fact that powers of five always end with five, I suppose then it's better to divide out the powers of two first than the powers of five. Tomorrow I will ++ both of these :D

Meh... I was actually only checking multiples of five. D'oh! 1/15 was reporting "Y".

Fixed...

```@ARGV = (15, 40);

sub _{@i=sort{\$b-\$a}@_;return\$i[1]if\$i[0]==\$i[1];@i=(\$i[1],\$i[0]%\$i[1
])while\$i[1];\$i[0]}sub __{\$j=_@_;\$_/=\$j for@_;\$_[1]<0and do{\$_*=-1for
@_}}__((\$k,\$l)=@ARGV);for(2,5){\$l/=\$_ until\$l%\$_}print\$l eq 1?Y:N,\$/#
perl -E'sub Monkey::do{say\$_,for@_,do{(\$monkey=[caller(0)]->[3])=~s{::}{ }and\$monkey}}"Monkey say"->Monkey::do'
Re^3: Determining if a rational number terminates
by pemungkah (Priest) on Dec 03, 2012 at 01:34 UTC
+1 for ironic comment on comments.

As we all know, the uncommented part is the part that needs the comment here. (And if you say "the code is obvious and needs no comments", it's my sincere opinion you need to get out more.)

Actually, if you fix up the whitespace and rename the functions:

• _ => highest_common_factor
• __ => canonical_fraction

perl -E'sub Monkey::do{say\$_,for@_,do{(\$monkey=[caller(0)]->[3])=~s{::}{ }and\$monkey}}"Monkey say"->Monkey::do'

Create A New User
Node Status?
node history
Node Type: note [id://1006301]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2018-06-21 20:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Should cpanminus be part of the standard Perl release?

Results (119 votes). Check out past polls.

Notices?