Problema
Using the integers from 1 through n, calculate two quantities: first add the integers and square the result; separately square each integer and add those squares. Return the first quantity minus the second.
Implement difference_of_squares(n).
Input
n: The last integer to include.
Output
Return square-of-sum minus sum-of-squares.
Restrições
0 ≤ n ≤ 50,000. For n = 0, both sums are 0. All required values fit signed 64-bit integers.
Exemplos
Entrada:
n = 4
Saída esperada:
expected = 70
Entrada:
long long n = 4;
Saída esperada:
long long expected = 70;
Entrada:
long n = 4;
Saída esperada:
long expected = 70;
Explicação
(1 + 2 + 3 + 4)² = 100. The sum of squares is 1 + 4 + 9 + 16 = 30. Subtract: 100 − 30 = 70.
Entrada:
n = 1
Saída esperada:
expected = 0
Entrada:
long long n = 1;
Saída esperada:
long long expected = 0;
Entrada:
long n = 1;
Saída esperada:
long expected = 0;
Explicação
Both quantities equal 1, so their difference is 0.
Como abordar
Tente sozinho primeiro e depois abra uma dica de cada vez.
Dica 1
You are comparing two summaries of the same range: one based on summing first, the other based on squaring first.
Dica 2
Use the closed-form expressions for sums of integers and sums of squares instead of looping through every value.
Dica 3
Handle the zero case carefully, since both quantities should be zero there.
Complexidade esperada
O(1) time, O(1) extra space
Referências
Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.