Thanks for the tip on $b=$a... although I was looking for all possible permutations (ok to switch values for $a and $b), it helps to only grab unique. Guess I could toss an ARGV in for "uniqueness".

As far as the square root, you could also use the built-in sqrt() function. Although yes, I'm still trying to alleviate the float problem (without using modules). ;-)

-fuzzyping

UPDATE:

Just realized my original logic with the $c loop was greatly flawed as well... it's limited by $max. For example, where $max=10, it should find:

3 4 5 is a winner
6 8 10 is a winner

But it was only finding /3 4 5/ due to the limit on $c (duh). Removing the $c loop has helped, but required me to cheat on the final confirmation (I didn't want to use any modules). Using sqrt and then avoiding any floats is the answer, but requires that I test $c as a string. :-(

#!/usr/bin/perl use strict; my ($a, $b, $c); my $max = shift || die "Usage: pythag.pl <max len>\n"; for ($a=1; $a<$max; $a++) { for ($b=$a; $b<$max; $b++) { $c = sqrt(($a**2) + ($b**2)); unless ($c =~ /\./) { print "$a $b $c is a winner\n"; } } }
The final result is only one line smaller, but saves .243ms per successful match.

-fuzzyping

UPDATE:

Thanks to tye and Sinister (don't know how I missed it before), I've implemented the int() check instead (keeping it within the numeric handling constraints I prefer)...

#!/usr/bin/perl use strict; my ($a, $b, $c); my $max = shift || die "Usage: pythag.pl <max len>\n"; for ($a=1; $a<$max; $a++) { for ($b=$a; $b<$max; $b++) { $c = sqrt(($a**2) + ($b**2)); if (int($c) == $c) { print "$a $b $c is a winner\n"; } } }
Thanks to all!

-fuzzyping

In reply to Re: Re: Pythagorean's theorem by fuzzyping
in thread Pythagorean's theorem by fuzzyping

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.