Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Finding sum of all digits from 1 to 1 million.

by bmcatt (Friar)
on Jan 24, 2002 at 00:31 UTC ( [id://141014]=note: print w/replies, xml ) Need Help??


in reply to Finding sum of all digits from 1 to 1 million.

Ummm... You're actually close, although you're off by 1. Fencepost error - you're terminating the loop one too early, so you're not including 1e6 in the loop. When in doubt, let perl figure out the right way to do it for you:

A slightly modified version:

#!/usr/bin/perl -w use strict; # or die :-) my $LIMIT = 1000000; my $s; foreach (1 .. $LIMIT) { foreach (/./g) { $s += $_; } } print "Sum: $s\n";

Golfers invited to make this even nicer (not to mention make it run faster...)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://141014]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-04-16 19:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found