Here is a simulation approach:
use strict; use warnings; my $n = shift; my $sum = 0; my $count = 0; while( $sum != ($n+1)*$n/2 ) { $sum = 1 + int( rand( $n**2 ) ); $count++; } print "Sum of 1 to $n: $sum (found after $count iterations)\n";
In reply to Re: How do I write a program that calculates the sum of all numbers to a number, n?
by hdb
in thread How do I write a program that calculates the sum of all numbers to a number, n?
by fmny94
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |