in reply to How do I write a program that calculates the sum of all numbers to a number, n?

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";
  • Comment on Re: How do I write a program that calculates the sum of all numbers to a number, n?
  • Download Code