Created
January 5, 2020 17:38
-
-
Save andrewsolomon/51976dc6204d2d44745d1671231a2e01 to your computer and use it in GitHub Desktop.
ways of calculating the sum of 1 to n
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use feature 'say'; | |
# To extend this to infinity, read: | |
# https://medium.com/cantors-paradise/the-ramanujan-summation-1-2-3-1-12-a8cc23dea793 | |
# For loop | |
sub v1_sum_one_to_n { | |
my $n = shift; | |
my $sum = 0; | |
foreach my $num (1 .. $n) { | |
$sum += $num; | |
} | |
return $sum; | |
} | |
# recursion | |
sub v2_sum_one_to_n { | |
my $n = shift; | |
return 1 if $n == 1; | |
return return $n + v2_sum_one_to_n($n-1); | |
} | |
# mathematics | |
sub v3_sum_one_to_n { | |
my $n = shift; | |
return $n * ($n + 1) / 2; | |
} | |
my $num = $ARGV[0]; | |
die "Invald arg $num" unless $num && $num > 0 && int($num) == $num; | |
say "For loop: " . v1_sum_one_to_n($num); | |
say "Recursion: " . v2_sum_one_to_n($num); | |
say "Mathematics: " . v3_sum_one_to_n($num); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment