in reply to Cube/digit script.
I assume you have a sum() function defined somewhere. And your variable scoping leaves something to be desired -- specifically, proper variable scoping. Rewriting only the scoping of your program, I'd do:
I have another comment. Why did you use 'for' in one loop and 'foreach' in another? They're not different things, and you're not using the C-style loop, so there's no reason one of them should have a different name from the other.my @numbers; for my $i (100 .. 999) { my @num = split(//, $i); foreach my $j (@num) { $j **= 3; } if (sum(@num) == $i) { push @numbers, $i; } }
All in all, I would rewrite this program to use far fewer temporary variables:
That might be a bit too succinct for you, but it does the same thing as yours.my @numbers = grep { sum(map { $_ ** 3 } split //) == $_ } 100 .. 999;
|
|---|