i suggest using a bit vector for storage (see vec.) use one bit per number to store whether it's triangular or not. i'll leave it as an excersize to figure out the details of my implementation.

#!/usr/bin/perl -w use strict; $|++; my $number = $ARGV[0] || die("Usage: trivec.pl number$/"); my $vecTri; $vecTri = createTriVec( $number ); print $/, findTriCombo( $vecTri, $number ); sub createTriVec { my $upper = $_[0] || 99; my $vec = "\0"; my $guess = 0; for( my $num = 1; $guess+$num <= $upper; $num++ ) { $guess+=$num; vec( $vec, $guess, 1 ) = 1; } return $vec; } sub findTriCombo { my $vec = $_[0] || return undef; my $num = $_[1] || return undef; my @tris; my $sum = 0; push(@tris, $num, 0, 0), return "@tris" if( vec( $vec, $num, 1 ) ) +; my $i = $num-1; while( $i > 0 ) { # print "<i $i>\t<s $sum>\t<t @tris>$/"; # UNCOMMENT TO SEE WHAT'S GOI +NG ON... if( scalar @tris >= 3 ) { $i = $tris[0] - 1; @tris = (); $sum = 0; } if( vec( $vec, $i, 1 ) ) { push @tris, $i; $sum += $i; $i = $num - $sum; next; } else { $i--; } } if( $sum == $num ) { push(@tris, 0) while @tris < 3; return "@tris"; } return "not found!"; }
Update: changes as per YuckFoo (below)

Update 2: always returns an array of length three (below)

~Particle ;Þ


In reply to Re: Triangle Numbers by particle
in thread Triangle Numbers by YuckFoo

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.