in reply to Cube/digit script.

Hi Andrew_Levenson

update:

I misread the spec. The sum() threw me.

The corrected output is

153 370 371 407
Here's my take on it :-)

Do you have a sub called sum? I've taken the liberty of assuming you may not.

I've also taken on board japhy's point about scoping and the for loop.

You're not storing the cubes anywhere so I've added a var to hold it.

There is, however, a slight snag. It only finds three!

666 870 960
With the code straigtened out a bit perhaps you can identify the error?

#!/bin/perl5 use strict; use warnings; my @numbers; for my $i (100..999){ my @num = split(//, $i); my $cubed; for my $j (@num){ $cubed += $j**3; } #my $added; #$added += $_ for @num; #print "$i -> $cubed -> $added\n"; if( ($cubed) == $i ){ push @numbers, $i; } } print "$_\n" for @numbers;

Hope this helps

Replies are listed 'Best First'.
Re^2: Cube/digit script.
by Andrew_Levenson (Hermit) on Mar 10, 2006 at 14:11 UTC
    Ooh, not only does it only find 3, but the three it finds are wrong. O_O There must be an error in my math, i'll have to check that out.
Re^2: Cube/digit script.
by Andrew_Levenson (Hermit) on Mar 10, 2006 at 14:21 UTC
    Here, I figured out what was wrong.
    The $added variable was unnecessary:
    use strict; use warnings; my $i; my $j; my $cubed; my @num; my @numbers; for $i(100..999){ undef($cubed); undef(@num); @num=split(//, $i); for $j(@num){ $cubed+=$j**3; } if($cubed==$i){ push @numbers, $i; } } print "$_\n" for @numbers;
    Thanks for the help!