平方和差

作者:polettix

https://projecteuler.net/problem=6

前十个自然数的平方和是:

1**2 + 2**2 + ... + 10**2 = 385

前十个自然数的和的平方是:

(1 + 2 + ... + 10)**2 = 55**2 = 3025

因此,前十个自然数的平方和与和的平方之差是 3025 - 385 = 2640。

求前一百个自然数的平方和与和的平方之差。

源代码:prob006-polettix.pl

use v6;

# Upper bound optionally taken from command line, defaults to
# challenge's request
my $upper = shift(@*ARGS) || 100;

# This is quite straightforward: the sum of the first N positive
# integers is easily computed as (N + 1) * N / 2, hence the square
# is straightforward. We then subtract the square of each single
# one to get the final result.
my $result = (($upper + 1) * $upper / 2) ** 2;
$result -= $_ ** 2 for 1 .. $upper;
say $result;