arithmetic_sum_closed_form.pl 726 B

12345678910111213141516171819202122232425262728293031
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 20 November 2017
  5. # https://github.com/trizen
  6. # Compute the sum of an arithmetic sequence.
  7. # Example: arithmetic_sum_*(1,3,1) returns 6 because 1+2+3 = 6
  8. # arithmetic_sum_*(1,7,2) returns 16 because 1+3+5+7 = 16
  9. # arithmetic_sum_*(begin, end, step)
  10. use 5.010;
  11. use strict;
  12. use warnings;
  13. use experimental qw(signatures);
  14. sub arithmetic_sum_continuous ($x, $y, $z) {
  15. ($x + $y) * (($y - $x) / $z + 1) / 2;
  16. }
  17. sub arithmetic_sum_discrete ($x, $y, $z) {
  18. (int(($y - $x) / $z) + 1) * ($z * int(($y - $x) / $z) + 2 * $x) / 2;
  19. }
  20. say arithmetic_sum_continuous(10, 113, 6); #=> 1117.25
  21. say arithmetic_sum_discrete(10, 113, 6); #=> 1098